LCOV - code coverage report
Current view: top level - src/crypto - tls_openssl.c (source / functions) Hit Total Coverage
Test: wpa_supplicant/hostapd combined for hwsim test run 1475438200 Lines: 1204 1527 78.8 %
Date: 2016-10-02 Functions: 78 83 94.0 %

          Line data    Source code
       1             : /*
       2             :  * SSL/TLS interface functions for OpenSSL
       3             :  * Copyright (c) 2004-2015, Jouni Malinen <j@w1.fi>
       4             :  *
       5             :  * This software may be distributed under the terms of the BSD license.
       6             :  * See README for more details.
       7             :  */
       8             : 
       9             : #include "includes.h"
      10             : 
      11             : #ifndef CONFIG_SMARTCARD
      12             : #ifndef OPENSSL_NO_ENGINE
      13             : #ifndef ANDROID
      14             : #define OPENSSL_NO_ENGINE
      15             : #endif
      16             : #endif
      17             : #endif
      18             : 
      19             : #include <openssl/ssl.h>
      20             : #include <openssl/err.h>
      21             : #include <openssl/opensslv.h>
      22             : #include <openssl/pkcs12.h>
      23             : #include <openssl/x509v3.h>
      24             : #ifndef OPENSSL_NO_ENGINE
      25             : #include <openssl/engine.h>
      26             : #endif /* OPENSSL_NO_ENGINE */
      27             : #ifndef OPENSSL_NO_DSA
      28             : #include <openssl/dsa.h>
      29             : #endif
      30             : #ifndef OPENSSL_NO_DH
      31             : #include <openssl/dh.h>
      32             : #endif
      33             : 
      34             : #include "common.h"
      35             : #include "crypto.h"
      36             : #include "sha1.h"
      37             : #include "sha256.h"
      38             : #include "tls.h"
      39             : #include "tls_openssl.h"
      40             : 
      41             : #if !defined(CONFIG_FIPS) &&                             \
      42             :     (defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) ||   \
      43             :      defined(EAP_SERVER_FAST))
      44             : #define OPENSSL_NEED_EAP_FAST_PRF
      45             : #endif
      46             : 
      47             : #if defined(OPENSSL_IS_BORINGSSL)
      48             : /* stack_index_t is the return type of OpenSSL's sk_XXX_num() functions. */
      49             : typedef size_t stack_index_t;
      50             : #else
      51             : typedef int stack_index_t;
      52             : #endif
      53             : 
      54             : #ifdef SSL_set_tlsext_status_type
      55             : #ifndef OPENSSL_NO_TLSEXT
      56             : #define HAVE_OCSP
      57             : #include <openssl/ocsp.h>
      58             : #endif /* OPENSSL_NO_TLSEXT */
      59             : #endif /* SSL_set_tlsext_status_type */
      60             : 
      61             : #if (OPENSSL_VERSION_NUMBER < 0x10100000L || \
      62             :      defined(LIBRESSL_VERSION_NUMBER)) &&    \
      63             :     !defined(BORINGSSL_API_VERSION)
      64             : /*
      65             :  * SSL_get_client_random() and SSL_get_server_random() were added in OpenSSL
      66             :  * 1.1.0 and newer BoringSSL revisions. Provide compatibility wrappers for
      67             :  * older versions.
      68             :  */
      69             : 
      70        1058 : static size_t SSL_get_client_random(const SSL *ssl, unsigned char *out,
      71             :                                     size_t outlen)
      72             : {
      73        1058 :         if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
      74           0 :                 return 0;
      75        1058 :         os_memcpy(out, ssl->s3->client_random, SSL3_RANDOM_SIZE);
      76        1058 :         return SSL3_RANDOM_SIZE;
      77             : }
      78             : 
      79             : 
      80        1058 : static size_t SSL_get_server_random(const SSL *ssl, unsigned char *out,
      81             :                                     size_t outlen)
      82             : {
      83        1058 :         if (!ssl->s3 || outlen < SSL3_RANDOM_SIZE)
      84           0 :                 return 0;
      85        1058 :         os_memcpy(out, ssl->s3->server_random, SSL3_RANDOM_SIZE);
      86        1058 :         return SSL3_RANDOM_SIZE;
      87             : }
      88             : 
      89             : 
      90             : #ifdef OPENSSL_NEED_EAP_FAST_PRF
      91         230 : static size_t SSL_SESSION_get_master_key(const SSL_SESSION *session,
      92             :                                          unsigned char *out, size_t outlen)
      93             : {
      94         460 :         if (!session || session->master_key_length < 0 ||
      95         230 :             (size_t) session->master_key_length > outlen)
      96           0 :                 return 0;
      97         230 :         if ((size_t) session->master_key_length < outlen)
      98         230 :                 outlen = session->master_key_length;
      99         230 :         os_memcpy(out, session->master_key, outlen);
     100         230 :         return outlen;
     101             : }
     102             : #endif /* OPENSSL_NEED_EAP_FAST_PRF */
     103             : 
     104             : #endif
     105             : 
     106             : #ifdef ANDROID
     107             : #include <openssl/pem.h>
     108             : #include <keystore/keystore_get.h>
     109             : 
     110             : static BIO * BIO_from_keystore(const char *key)
     111             : {
     112             :         BIO *bio = NULL;
     113             :         uint8_t *value = NULL;
     114             :         int length = keystore_get(key, strlen(key), &value);
     115             :         if (length != -1 && (bio = BIO_new(BIO_s_mem())) != NULL)
     116             :                 BIO_write(bio, value, length);
     117             :         free(value);
     118             :         return bio;
     119             : }
     120             : 
     121             : 
     122             : static int tls_add_ca_from_keystore(X509_STORE *ctx, const char *key_alias)
     123             : {
     124             :         BIO *bio = BIO_from_keystore(key_alias);
     125             :         STACK_OF(X509_INFO) *stack = NULL;
     126             :         stack_index_t i;
     127             : 
     128             :         if (bio) {
     129             :                 stack = PEM_X509_INFO_read_bio(bio, NULL, NULL, NULL);
     130             :                 BIO_free(bio);
     131             :         }
     132             : 
     133             :         if (!stack) {
     134             :                 wpa_printf(MSG_WARNING, "TLS: Failed to parse certificate: %s",
     135             :                            key_alias);
     136             :                 return -1;
     137             :         }
     138             : 
     139             :         for (i = 0; i < sk_X509_INFO_num(stack); ++i) {
     140             :                 X509_INFO *info = sk_X509_INFO_value(stack, i);
     141             : 
     142             :                 if (info->x509)
     143             :                         X509_STORE_add_cert(ctx, info->x509);
     144             :                 if (info->crl)
     145             :                         X509_STORE_add_crl(ctx, info->crl);
     146             :         }
     147             : 
     148             :         sk_X509_INFO_pop_free(stack, X509_INFO_free);
     149             : 
     150             :         return 0;
     151             : }
     152             : 
     153             : 
     154             : static int tls_add_ca_from_keystore_encoded(X509_STORE *ctx,
     155             :                                             const char *encoded_key_alias)
     156             : {
     157             :         int rc = -1;
     158             :         int len = os_strlen(encoded_key_alias);
     159             :         unsigned char *decoded_alias;
     160             : 
     161             :         if (len & 1) {
     162             :                 wpa_printf(MSG_WARNING, "Invalid hex-encoded alias: %s",
     163             :                            encoded_key_alias);
     164             :                 return rc;
     165             :         }
     166             : 
     167             :         decoded_alias = os_malloc(len / 2 + 1);
     168             :         if (decoded_alias) {
     169             :                 if (!hexstr2bin(encoded_key_alias, decoded_alias, len / 2)) {
     170             :                         decoded_alias[len / 2] = '\0';
     171             :                         rc = tls_add_ca_from_keystore(
     172             :                                 ctx, (const char *) decoded_alias);
     173             :                 }
     174             :                 os_free(decoded_alias);
     175             :         }
     176             : 
     177             :         return rc;
     178             : }
     179             : 
     180             : #endif /* ANDROID */
     181             : 
     182             : static int tls_openssl_ref_count = 0;
     183             : static int tls_ex_idx_session = -1;
     184             : 
     185             : struct tls_context {
     186             :         void (*event_cb)(void *ctx, enum tls_event ev,
     187             :                          union tls_event_data *data);
     188             :         void *cb_ctx;
     189             :         int cert_in_cb;
     190             :         char *ocsp_stapling_response;
     191             : };
     192             : 
     193             : static struct tls_context *tls_global = NULL;
     194             : 
     195             : 
     196             : struct tls_data {
     197             :         SSL_CTX *ssl;
     198             :         unsigned int tls_session_lifetime;
     199             : };
     200             : 
     201             : struct tls_connection {
     202             :         struct tls_context *context;
     203             :         SSL_CTX *ssl_ctx;
     204             :         SSL *ssl;
     205             :         BIO *ssl_in, *ssl_out;
     206             : #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
     207             :         ENGINE *engine;        /* functional reference to the engine */
     208             :         EVP_PKEY *private_key; /* the private key if using engine */
     209             : #endif /* OPENSSL_NO_ENGINE */
     210             :         char *subject_match, *altsubject_match, *suffix_match, *domain_match;
     211             :         int read_alerts, write_alerts, failed;
     212             : 
     213             :         tls_session_ticket_cb session_ticket_cb;
     214             :         void *session_ticket_cb_ctx;
     215             : 
     216             :         /* SessionTicket received from OpenSSL hello_extension_cb (server) */
     217             :         u8 *session_ticket;
     218             :         size_t session_ticket_len;
     219             : 
     220             :         unsigned int ca_cert_verify:1;
     221             :         unsigned int cert_probe:1;
     222             :         unsigned int server_cert_only:1;
     223             :         unsigned int invalid_hb_used:1;
     224             :         unsigned int success_data:1;
     225             : 
     226             :         u8 srv_cert_hash[32];
     227             : 
     228             :         unsigned int flags;
     229             : 
     230             :         X509 *peer_cert;
     231             :         X509 *peer_issuer;
     232             :         X509 *peer_issuer_issuer;
     233             : 
     234             :         unsigned char client_random[SSL3_RANDOM_SIZE];
     235             :         unsigned char server_random[SSL3_RANDOM_SIZE];
     236             : };
     237             : 
     238             : 
     239        1568 : static struct tls_context * tls_context_new(const struct tls_config *conf)
     240             : {
     241        1568 :         struct tls_context *context = os_zalloc(sizeof(*context));
     242        1568 :         if (context == NULL)
     243           4 :                 return NULL;
     244        1564 :         if (conf) {
     245        1564 :                 context->event_cb = conf->event_cb;
     246        1564 :                 context->cb_ctx = conf->cb_ctx;
     247        1564 :                 context->cert_in_cb = conf->cert_in_cb;
     248             :         }
     249        1564 :         return context;
     250             : }
     251             : 
     252             : 
     253             : #ifdef CONFIG_NO_STDOUT_DEBUG
     254             : 
     255             : static void _tls_show_errors(void)
     256             : {
     257             :         unsigned long err;
     258             : 
     259             :         while ((err = ERR_get_error())) {
     260             :                 /* Just ignore the errors, since stdout is disabled */
     261             :         }
     262             : }
     263             : #define tls_show_errors(l, f, t) _tls_show_errors()
     264             : 
     265             : #else /* CONFIG_NO_STDOUT_DEBUG */
     266             : 
     267          99 : static void tls_show_errors(int level, const char *func, const char *txt)
     268             : {
     269             :         unsigned long err;
     270             : 
     271          99 :         wpa_printf(level, "OpenSSL: %s - %s %s",
     272             :                    func, txt, ERR_error_string(ERR_get_error(), NULL));
     273             : 
     274         203 :         while ((err = ERR_get_error())) {
     275           5 :                 wpa_printf(MSG_INFO, "OpenSSL: pending error: %s",
     276             :                            ERR_error_string(err, NULL));
     277             :         }
     278          99 : }
     279             : 
     280             : #endif /* CONFIG_NO_STDOUT_DEBUG */
     281             : 
     282             : 
     283             : #ifdef CONFIG_NATIVE_WINDOWS
     284             : 
     285             : /* Windows CryptoAPI and access to certificate stores */
     286             : #include <wincrypt.h>
     287             : 
     288             : #ifdef __MINGW32_VERSION
     289             : /*
     290             :  * MinGW does not yet include all the needed definitions for CryptoAPI, so
     291             :  * define here whatever extra is needed.
     292             :  */
     293             : #define CERT_SYSTEM_STORE_CURRENT_USER (1 << 16)
     294             : #define CERT_STORE_READONLY_FLAG 0x00008000
     295             : #define CERT_STORE_OPEN_EXISTING_FLAG 0x00004000
     296             : 
     297             : #endif /* __MINGW32_VERSION */
     298             : 
     299             : 
     300             : struct cryptoapi_rsa_data {
     301             :         const CERT_CONTEXT *cert;
     302             :         HCRYPTPROV crypt_prov;
     303             :         DWORD key_spec;
     304             :         BOOL free_crypt_prov;
     305             : };
     306             : 
     307             : 
     308             : static void cryptoapi_error(const char *msg)
     309             : {
     310             :         wpa_printf(MSG_INFO, "CryptoAPI: %s; err=%u",
     311             :                    msg, (unsigned int) GetLastError());
     312             : }
     313             : 
     314             : 
     315             : static int cryptoapi_rsa_pub_enc(int flen, const unsigned char *from,
     316             :                                  unsigned char *to, RSA *rsa, int padding)
     317             : {
     318             :         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
     319             :         return 0;
     320             : }
     321             : 
     322             : 
     323             : static int cryptoapi_rsa_pub_dec(int flen, const unsigned char *from,
     324             :                                  unsigned char *to, RSA *rsa, int padding)
     325             : {
     326             :         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
     327             :         return 0;
     328             : }
     329             : 
     330             : 
     331             : static int cryptoapi_rsa_priv_enc(int flen, const unsigned char *from,
     332             :                                   unsigned char *to, RSA *rsa, int padding)
     333             : {
     334             :         struct cryptoapi_rsa_data *priv =
     335             :                 (struct cryptoapi_rsa_data *) rsa->meth->app_data;
     336             :         HCRYPTHASH hash;
     337             :         DWORD hash_size, len, i;
     338             :         unsigned char *buf = NULL;
     339             :         int ret = 0;
     340             : 
     341             :         if (priv == NULL) {
     342             :                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
     343             :                        ERR_R_PASSED_NULL_PARAMETER);
     344             :                 return 0;
     345             :         }
     346             : 
     347             :         if (padding != RSA_PKCS1_PADDING) {
     348             :                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
     349             :                        RSA_R_UNKNOWN_PADDING_TYPE);
     350             :                 return 0;
     351             :         }
     352             : 
     353             :         if (flen != 16 /* MD5 */ + 20 /* SHA-1 */) {
     354             :                 wpa_printf(MSG_INFO, "%s - only MD5-SHA1 hash supported",
     355             :                            __func__);
     356             :                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
     357             :                        RSA_R_INVALID_MESSAGE_LENGTH);
     358             :                 return 0;
     359             :         }
     360             : 
     361             :         if (!CryptCreateHash(priv->crypt_prov, CALG_SSL3_SHAMD5, 0, 0, &hash))
     362             :         {
     363             :                 cryptoapi_error("CryptCreateHash failed");
     364             :                 return 0;
     365             :         }
     366             : 
     367             :         len = sizeof(hash_size);
     368             :         if (!CryptGetHashParam(hash, HP_HASHSIZE, (BYTE *) &hash_size, &len,
     369             :                                0)) {
     370             :                 cryptoapi_error("CryptGetHashParam failed");
     371             :                 goto err;
     372             :         }
     373             : 
     374             :         if ((int) hash_size != flen) {
     375             :                 wpa_printf(MSG_INFO, "CryptoAPI: Invalid hash size (%u != %d)",
     376             :                            (unsigned) hash_size, flen);
     377             :                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT,
     378             :                        RSA_R_INVALID_MESSAGE_LENGTH);
     379             :                 goto err;
     380             :         }
     381             :         if (!CryptSetHashParam(hash, HP_HASHVAL, (BYTE * ) from, 0)) {
     382             :                 cryptoapi_error("CryptSetHashParam failed");
     383             :                 goto err;
     384             :         }
     385             : 
     386             :         len = RSA_size(rsa);
     387             :         buf = os_malloc(len);
     388             :         if (buf == NULL) {
     389             :                 RSAerr(RSA_F_RSA_EAY_PRIVATE_ENCRYPT, ERR_R_MALLOC_FAILURE);
     390             :                 goto err;
     391             :         }
     392             : 
     393             :         if (!CryptSignHash(hash, priv->key_spec, NULL, 0, buf, &len)) {
     394             :                 cryptoapi_error("CryptSignHash failed");
     395             :                 goto err;
     396             :         }
     397             : 
     398             :         for (i = 0; i < len; i++)
     399             :                 to[i] = buf[len - i - 1];
     400             :         ret = len;
     401             : 
     402             : err:
     403             :         os_free(buf);
     404             :         CryptDestroyHash(hash);
     405             : 
     406             :         return ret;
     407             : }
     408             : 
     409             : 
     410             : static int cryptoapi_rsa_priv_dec(int flen, const unsigned char *from,
     411             :                                   unsigned char *to, RSA *rsa, int padding)
     412             : {
     413             :         wpa_printf(MSG_DEBUG, "%s - not implemented", __func__);
     414             :         return 0;
     415             : }
     416             : 
     417             : 
     418             : static void cryptoapi_free_data(struct cryptoapi_rsa_data *priv)
     419             : {
     420             :         if (priv == NULL)
     421             :                 return;
     422             :         if (priv->crypt_prov && priv->free_crypt_prov)
     423             :                 CryptReleaseContext(priv->crypt_prov, 0);
     424             :         if (priv->cert)
     425             :                 CertFreeCertificateContext(priv->cert);
     426             :         os_free(priv);
     427             : }
     428             : 
     429             : 
     430             : static int cryptoapi_finish(RSA *rsa)
     431             : {
     432             :         cryptoapi_free_data((struct cryptoapi_rsa_data *) rsa->meth->app_data);
     433             :         os_free((void *) rsa->meth);
     434             :         rsa->meth = NULL;
     435             :         return 1;
     436             : }
     437             : 
     438             : 
     439             : static const CERT_CONTEXT * cryptoapi_find_cert(const char *name, DWORD store)
     440             : {
     441             :         HCERTSTORE cs;
     442             :         const CERT_CONTEXT *ret = NULL;
     443             : 
     444             :         cs = CertOpenStore((LPCSTR) CERT_STORE_PROV_SYSTEM, 0, 0,
     445             :                            store | CERT_STORE_OPEN_EXISTING_FLAG |
     446             :                            CERT_STORE_READONLY_FLAG, L"MY");
     447             :         if (cs == NULL) {
     448             :                 cryptoapi_error("Failed to open 'My system store'");
     449             :                 return NULL;
     450             :         }
     451             : 
     452             :         if (strncmp(name, "cert://", 7) == 0) {
     453             :                 unsigned short wbuf[255];
     454             :                 MultiByteToWideChar(CP_ACP, 0, name + 7, -1, wbuf, 255);
     455             :                 ret = CertFindCertificateInStore(cs, X509_ASN_ENCODING |
     456             :                                                  PKCS_7_ASN_ENCODING,
     457             :                                                  0, CERT_FIND_SUBJECT_STR,
     458             :                                                  wbuf, NULL);
     459             :         } else if (strncmp(name, "hash://", 7) == 0) {
     460             :                 CRYPT_HASH_BLOB blob;
     461             :                 int len;
     462             :                 const char *hash = name + 7;
     463             :                 unsigned char *buf;
     464             : 
     465             :                 len = os_strlen(hash) / 2;
     466             :                 buf = os_malloc(len);
     467             :                 if (buf && hexstr2bin(hash, buf, len) == 0) {
     468             :                         blob.cbData = len;
     469             :                         blob.pbData = buf;
     470             :                         ret = CertFindCertificateInStore(cs,
     471             :                                                          X509_ASN_ENCODING |
     472             :                                                          PKCS_7_ASN_ENCODING,
     473             :                                                          0, CERT_FIND_HASH,
     474             :                                                          &blob, NULL);
     475             :                 }
     476             :                 os_free(buf);
     477             :         }
     478             : 
     479             :         CertCloseStore(cs, 0);
     480             : 
     481             :         return ret;
     482             : }
     483             : 
     484             : 
     485             : static int tls_cryptoapi_cert(SSL *ssl, const char *name)
     486             : {
     487             :         X509 *cert = NULL;
     488             :         RSA *rsa = NULL, *pub_rsa;
     489             :         struct cryptoapi_rsa_data *priv;
     490             :         RSA_METHOD *rsa_meth;
     491             : 
     492             :         if (name == NULL ||
     493             :             (strncmp(name, "cert://", 7) != 0 &&
     494             :              strncmp(name, "hash://", 7) != 0))
     495             :                 return -1;
     496             : 
     497             :         priv = os_zalloc(sizeof(*priv));
     498             :         rsa_meth = os_zalloc(sizeof(*rsa_meth));
     499             :         if (priv == NULL || rsa_meth == NULL) {
     500             :                 wpa_printf(MSG_WARNING, "CryptoAPI: Failed to allocate memory "
     501             :                            "for CryptoAPI RSA method");
     502             :                 os_free(priv);
     503             :                 os_free(rsa_meth);
     504             :                 return -1;
     505             :         }
     506             : 
     507             :         priv->cert = cryptoapi_find_cert(name, CERT_SYSTEM_STORE_CURRENT_USER);
     508             :         if (priv->cert == NULL) {
     509             :                 priv->cert = cryptoapi_find_cert(
     510             :                         name, CERT_SYSTEM_STORE_LOCAL_MACHINE);
     511             :         }
     512             :         if (priv->cert == NULL) {
     513             :                 wpa_printf(MSG_INFO, "CryptoAPI: Could not find certificate "
     514             :                            "'%s'", name);
     515             :                 goto err;
     516             :         }
     517             : 
     518             :         cert = d2i_X509(NULL,
     519             :                         (const unsigned char **) &priv->cert->pbCertEncoded,
     520             :                         priv->cert->cbCertEncoded);
     521             :         if (cert == NULL) {
     522             :                 wpa_printf(MSG_INFO, "CryptoAPI: Could not process X509 DER "
     523             :                            "encoding");
     524             :                 goto err;
     525             :         }
     526             : 
     527             :         if (!CryptAcquireCertificatePrivateKey(priv->cert,
     528             :                                                CRYPT_ACQUIRE_COMPARE_KEY_FLAG,
     529             :                                                NULL, &priv->crypt_prov,
     530             :                                                &priv->key_spec,
     531             :                                                &priv->free_crypt_prov)) {
     532             :                 cryptoapi_error("Failed to acquire a private key for the "
     533             :                                 "certificate");
     534             :                 goto err;
     535             :         }
     536             : 
     537             :         rsa_meth->name = "Microsoft CryptoAPI RSA Method";
     538             :         rsa_meth->rsa_pub_enc = cryptoapi_rsa_pub_enc;
     539             :         rsa_meth->rsa_pub_dec = cryptoapi_rsa_pub_dec;
     540             :         rsa_meth->rsa_priv_enc = cryptoapi_rsa_priv_enc;
     541             :         rsa_meth->rsa_priv_dec = cryptoapi_rsa_priv_dec;
     542             :         rsa_meth->finish = cryptoapi_finish;
     543             :         rsa_meth->flags = RSA_METHOD_FLAG_NO_CHECK;
     544             :         rsa_meth->app_data = (char *) priv;
     545             : 
     546             :         rsa = RSA_new();
     547             :         if (rsa == NULL) {
     548             :                 SSLerr(SSL_F_SSL_CTX_USE_CERTIFICATE_FILE,
     549             :                        ERR_R_MALLOC_FAILURE);
     550             :                 goto err;
     551             :         }
     552             : 
     553             :         if (!SSL_use_certificate(ssl, cert)) {
     554             :                 RSA_free(rsa);
     555             :                 rsa = NULL;
     556             :                 goto err;
     557             :         }
     558             :         pub_rsa = cert->cert_info->key->pkey->pkey.rsa;
     559             :         X509_free(cert);
     560             :         cert = NULL;
     561             : 
     562             :         rsa->n = BN_dup(pub_rsa->n);
     563             :         rsa->e = BN_dup(pub_rsa->e);
     564             :         if (!RSA_set_method(rsa, rsa_meth))
     565             :                 goto err;
     566             : 
     567             :         if (!SSL_use_RSAPrivateKey(ssl, rsa))
     568             :                 goto err;
     569             :         RSA_free(rsa);
     570             : 
     571             :         return 0;
     572             : 
     573             : err:
     574             :         if (cert)
     575             :                 X509_free(cert);
     576             :         if (rsa)
     577             :                 RSA_free(rsa);
     578             :         else {
     579             :                 os_free(rsa_meth);
     580             :                 cryptoapi_free_data(priv);
     581             :         }
     582             :         return -1;
     583             : }
     584             : 
     585             : 
     586             : static int tls_cryptoapi_ca_cert(SSL_CTX *ssl_ctx, SSL *ssl, const char *name)
     587             : {
     588             :         HCERTSTORE cs;
     589             :         PCCERT_CONTEXT ctx = NULL;
     590             :         X509 *cert;
     591             :         char buf[128];
     592             :         const char *store;
     593             : #ifdef UNICODE
     594             :         WCHAR *wstore;
     595             : #endif /* UNICODE */
     596             : 
     597             :         if (name == NULL || strncmp(name, "cert_store://", 13) != 0)
     598             :                 return -1;
     599             : 
     600             :         store = name + 13;
     601             : #ifdef UNICODE
     602             :         wstore = os_malloc((os_strlen(store) + 1) * sizeof(WCHAR));
     603             :         if (wstore == NULL)
     604             :                 return -1;
     605             :         wsprintf(wstore, L"%S", store);
     606             :         cs = CertOpenSystemStore(0, wstore);
     607             :         os_free(wstore);
     608             : #else /* UNICODE */
     609             :         cs = CertOpenSystemStore(0, store);
     610             : #endif /* UNICODE */
     611             :         if (cs == NULL) {
     612             :                 wpa_printf(MSG_DEBUG, "%s: failed to open system cert store "
     613             :                            "'%s': error=%d", __func__, store,
     614             :                            (int) GetLastError());
     615             :                 return -1;
     616             :         }
     617             : 
     618             :         while ((ctx = CertEnumCertificatesInStore(cs, ctx))) {
     619             :                 cert = d2i_X509(NULL,
     620             :                                 (const unsigned char **) &ctx->pbCertEncoded,
     621             :                                 ctx->cbCertEncoded);
     622             :                 if (cert == NULL) {
     623             :                         wpa_printf(MSG_INFO, "CryptoAPI: Could not process "
     624             :                                    "X509 DER encoding for CA cert");
     625             :                         continue;
     626             :                 }
     627             : 
     628             :                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
     629             :                                   sizeof(buf));
     630             :                 wpa_printf(MSG_DEBUG, "OpenSSL: Loaded CA certificate for "
     631             :                            "system certificate store: subject='%s'", buf);
     632             : 
     633             :                 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
     634             :                                          cert)) {
     635             :                         tls_show_errors(MSG_WARNING, __func__,
     636             :                                         "Failed to add ca_cert to OpenSSL "
     637             :                                         "certificate store");
     638             :                 }
     639             : 
     640             :                 X509_free(cert);
     641             :         }
     642             : 
     643             :         if (!CertCloseStore(cs, 0)) {
     644             :                 wpa_printf(MSG_DEBUG, "%s: failed to close system cert store "
     645             :                            "'%s': error=%d", __func__, name + 13,
     646             :                            (int) GetLastError());
     647             :         }
     648             : 
     649             :         return 0;
     650             : }
     651             : 
     652             : 
     653             : #else /* CONFIG_NATIVE_WINDOWS */
     654             : 
     655           1 : static int tls_cryptoapi_cert(SSL *ssl, const char *name)
     656             : {
     657           1 :         return -1;
     658             : }
     659             : 
     660             : #endif /* CONFIG_NATIVE_WINDOWS */
     661             : 
     662             : 
     663       19088 : static void ssl_info_cb(const SSL *ssl, int where, int ret)
     664             : {
     665             :         const char *str;
     666             :         int w;
     667             : 
     668       19088 :         wpa_printf(MSG_DEBUG, "SSL: (where=0x%x ret=0x%x)", where, ret);
     669       19088 :         w = where & ~SSL_ST_MASK;
     670       19088 :         if (w & SSL_ST_CONNECT)
     671        8245 :                 str = "SSL_connect";
     672       10843 :         else if (w & SSL_ST_ACCEPT)
     673        8540 :                 str = "SSL_accept";
     674             :         else
     675        2303 :                 str = "undefined";
     676             : 
     677       19088 :         if (where & SSL_CB_LOOP) {
     678       12999 :                 wpa_printf(MSG_DEBUG, "SSL: %s:%s",
     679             :                            str, SSL_state_string_long(ssl));
     680        6089 :         } else if (where & SSL_CB_ALERT) {
     681          67 :                 struct tls_connection *conn = SSL_get_app_data((SSL *) ssl);
     682         134 :                 wpa_printf(MSG_INFO, "SSL: SSL3 alert: %s:%s:%s",
     683          67 :                            where & SSL_CB_READ ?
     684             :                            "read (remote end reported an error)" :
     685             :                            "write (local SSL3 detected an error)",
     686             :                            SSL_alert_type_string_long(ret),
     687             :                            SSL_alert_desc_string_long(ret));
     688          67 :                 if ((ret >> 8) == SSL3_AL_FATAL) {
     689          67 :                         if (where & SSL_CB_READ)
     690          31 :                                 conn->read_alerts++;
     691             :                         else
     692          36 :                                 conn->write_alerts++;
     693             :                 }
     694          67 :                 if (conn->context->event_cb != NULL) {
     695             :                         union tls_event_data ev;
     696          32 :                         struct tls_context *context = conn->context;
     697          32 :                         os_memset(&ev, 0, sizeof(ev));
     698          32 :                         ev.alert.is_local = !(where & SSL_CB_READ);
     699          32 :                         ev.alert.type = SSL_alert_type_string_long(ret);
     700          32 :                         ev.alert.description = SSL_alert_desc_string_long(ret);
     701          32 :                         context->event_cb(context->cb_ctx, TLS_ALERT, &ev);
     702             :                 }
     703        6022 :         } else if (where & SSL_CB_EXIT && ret <= 0) {
     704        2720 :                 wpa_printf(MSG_DEBUG, "SSL: %s:%s in %s",
     705             :                            str, ret == 0 ? "failed" : "error",
     706             :                            SSL_state_string_long(ssl));
     707             :         }
     708       19088 : }
     709             : 
     710             : 
     711             : #ifndef OPENSSL_NO_ENGINE
     712             : /**
     713             :  * tls_engine_load_dynamic_generic - load any openssl engine
     714             :  * @pre: an array of commands and values that load an engine initialized
     715             :  *       in the engine specific function
     716             :  * @post: an array of commands and values that initialize an already loaded
     717             :  *        engine (or %NULL if not required)
     718             :  * @id: the engine id of the engine to load (only required if post is not %NULL
     719             :  *
     720             :  * This function is a generic function that loads any openssl engine.
     721             :  *
     722             :  * Returns: 0 on success, -1 on failure
     723             :  */
     724             : static int tls_engine_load_dynamic_generic(const char *pre[],
     725             :                                            const char *post[], const char *id)
     726             : {
     727             :         ENGINE *engine;
     728             :         const char *dynamic_id = "dynamic";
     729             : 
     730             :         engine = ENGINE_by_id(id);
     731             :         if (engine) {
     732             :                 wpa_printf(MSG_DEBUG, "ENGINE: engine '%s' is already "
     733             :                            "available", id);
     734             :                 /*
     735             :                  * If it was auto-loaded by ENGINE_by_id() we might still
     736             :                  * need to tell it which PKCS#11 module to use in legacy
     737             :                  * (non-p11-kit) environments. Do so now; even if it was
     738             :                  * properly initialised before, setting it again will be
     739             :                  * harmless.
     740             :                  */
     741             :                 goto found;
     742             :         }
     743             :         ERR_clear_error();
     744             : 
     745             :         engine = ENGINE_by_id(dynamic_id);
     746             :         if (engine == NULL) {
     747             :                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
     748             :                            dynamic_id,
     749             :                            ERR_error_string(ERR_get_error(), NULL));
     750             :                 return -1;
     751             :         }
     752             : 
     753             :         /* Perform the pre commands. This will load the engine. */
     754             :         while (pre && pre[0]) {
     755             :                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", pre[0], pre[1]);
     756             :                 if (ENGINE_ctrl_cmd_string(engine, pre[0], pre[1], 0) == 0) {
     757             :                         wpa_printf(MSG_INFO, "ENGINE: ctrl cmd_string failed: "
     758             :                                    "%s %s [%s]", pre[0], pre[1],
     759             :                                    ERR_error_string(ERR_get_error(), NULL));
     760             :                         ENGINE_free(engine);
     761             :                         return -1;
     762             :                 }
     763             :                 pre += 2;
     764             :         }
     765             : 
     766             :         /*
     767             :          * Free the reference to the "dynamic" engine. The loaded engine can
     768             :          * now be looked up using ENGINE_by_id().
     769             :          */
     770             :         ENGINE_free(engine);
     771             : 
     772             :         engine = ENGINE_by_id(id);
     773             :         if (engine == NULL) {
     774             :                 wpa_printf(MSG_INFO, "ENGINE: Can't find engine %s [%s]",
     775             :                            id, ERR_error_string(ERR_get_error(), NULL));
     776             :                 return -1;
     777             :         }
     778             :  found:
     779             :         while (post && post[0]) {
     780             :                 wpa_printf(MSG_DEBUG, "ENGINE: '%s' '%s'", post[0], post[1]);
     781             :                 if (ENGINE_ctrl_cmd_string(engine, post[0], post[1], 0) == 0) {
     782             :                         wpa_printf(MSG_DEBUG, "ENGINE: ctrl cmd_string failed:"
     783             :                                 " %s %s [%s]", post[0], post[1],
     784             :                                    ERR_error_string(ERR_get_error(), NULL));
     785             :                         ENGINE_remove(engine);
     786             :                         ENGINE_free(engine);
     787             :                         return -1;
     788             :                 }
     789             :                 post += 2;
     790             :         }
     791             :         ENGINE_free(engine);
     792             : 
     793             :         return 0;
     794             : }
     795             : 
     796             : 
     797             : /**
     798             :  * tls_engine_load_dynamic_pkcs11 - load the pkcs11 engine provided by opensc
     799             :  * @pkcs11_so_path: pksc11_so_path from the configuration
     800             :  * @pcks11_module_path: pkcs11_module_path from the configuration
     801             :  */
     802             : static int tls_engine_load_dynamic_pkcs11(const char *pkcs11_so_path,
     803             :                                           const char *pkcs11_module_path)
     804             : {
     805             :         char *engine_id = "pkcs11";
     806             :         const char *pre_cmd[] = {
     807             :                 "SO_PATH", NULL /* pkcs11_so_path */,
     808             :                 "ID", NULL /* engine_id */,
     809             :                 "LIST_ADD", "1",
     810             :                 /* "NO_VCHECK", "1", */
     811             :                 "LOAD", NULL,
     812             :                 NULL, NULL
     813             :         };
     814             :         const char *post_cmd[] = {
     815             :                 "MODULE_PATH", NULL /* pkcs11_module_path */,
     816             :                 NULL, NULL
     817             :         };
     818             : 
     819             :         if (!pkcs11_so_path)
     820             :                 return 0;
     821             : 
     822             :         pre_cmd[1] = pkcs11_so_path;
     823             :         pre_cmd[3] = engine_id;
     824             :         if (pkcs11_module_path)
     825             :                 post_cmd[1] = pkcs11_module_path;
     826             :         else
     827             :                 post_cmd[0] = NULL;
     828             : 
     829             :         wpa_printf(MSG_DEBUG, "ENGINE: Loading pkcs11 Engine from %s",
     830             :                    pkcs11_so_path);
     831             : 
     832             :         return tls_engine_load_dynamic_generic(pre_cmd, post_cmd, engine_id);
     833             : }
     834             : 
     835             : 
     836             : /**
     837             :  * tls_engine_load_dynamic_opensc - load the opensc engine provided by opensc
     838             :  * @opensc_so_path: opensc_so_path from the configuration
     839             :  */
     840             : static int tls_engine_load_dynamic_opensc(const char *opensc_so_path)
     841             : {
     842             :         char *engine_id = "opensc";
     843             :         const char *pre_cmd[] = {
     844             :                 "SO_PATH", NULL /* opensc_so_path */,
     845             :                 "ID", NULL /* engine_id */,
     846             :                 "LIST_ADD", "1",
     847             :                 "LOAD", NULL,
     848             :                 NULL, NULL
     849             :         };
     850             : 
     851             :         if (!opensc_so_path)
     852             :                 return 0;
     853             : 
     854             :         pre_cmd[1] = opensc_so_path;
     855             :         pre_cmd[3] = engine_id;
     856             : 
     857             :         wpa_printf(MSG_DEBUG, "ENGINE: Loading OpenSC Engine from %s",
     858             :                    opensc_so_path);
     859             : 
     860             :         return tls_engine_load_dynamic_generic(pre_cmd, NULL, engine_id);
     861             : }
     862             : #endif /* OPENSSL_NO_ENGINE */
     863             : 
     864             : 
     865          11 : static void remove_session_cb(SSL_CTX *ctx, SSL_SESSION *sess)
     866             : {
     867             :         struct wpabuf *buf;
     868             : 
     869          11 :         if (tls_ex_idx_session < 0)
     870           0 :                 return;
     871          11 :         buf = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
     872          11 :         if (!buf)
     873           0 :                 return;
     874          11 :         wpa_printf(MSG_DEBUG,
     875             :                    "OpenSSL: Free application session data %p (sess %p)",
     876             :                    buf, sess);
     877          11 :         wpabuf_free(buf);
     878             : 
     879          11 :         SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, NULL);
     880             : }
     881             : 
     882             : 
     883        1568 : void * tls_init(const struct tls_config *conf)
     884             : {
     885             :         struct tls_data *data;
     886             :         SSL_CTX *ssl;
     887             :         struct tls_context *context;
     888             :         const char *ciphers;
     889             : 
     890        1568 :         if (tls_openssl_ref_count == 0) {
     891         426 :                 tls_global = context = tls_context_new(conf);
     892         426 :                 if (context == NULL)
     893           0 :                         return NULL;
     894             : #ifdef CONFIG_FIPS
     895             : #ifdef OPENSSL_FIPS
     896             :                 if (conf && conf->fips_mode) {
     897             :                         static int fips_enabled = 0;
     898             : 
     899             :                         if (!fips_enabled && !FIPS_mode_set(1)) {
     900             :                                 wpa_printf(MSG_ERROR, "Failed to enable FIPS "
     901             :                                            "mode");
     902             :                                 ERR_load_crypto_strings();
     903             :                                 ERR_print_errors_fp(stderr);
     904             :                                 os_free(tls_global);
     905             :                                 tls_global = NULL;
     906             :                                 return NULL;
     907             :                         } else {
     908             :                                 wpa_printf(MSG_INFO, "Running in FIPS mode");
     909             :                                 fips_enabled = 1;
     910             :                         }
     911             :                 }
     912             : #else /* OPENSSL_FIPS */
     913             :                 if (conf && conf->fips_mode) {
     914             :                         wpa_printf(MSG_ERROR, "FIPS mode requested, but not "
     915             :                                    "supported");
     916             :                         os_free(tls_global);
     917             :                         tls_global = NULL;
     918             :                         return NULL;
     919             :                 }
     920             : #endif /* OPENSSL_FIPS */
     921             : #endif /* CONFIG_FIPS */
     922             : #if OPENSSL_VERSION_NUMBER < 0x10100000L
     923         426 :                 SSL_load_error_strings();
     924         426 :                 SSL_library_init();
     925             : #ifndef OPENSSL_NO_SHA256
     926         426 :                 EVP_add_digest(EVP_sha256());
     927             : #endif /* OPENSSL_NO_SHA256 */
     928             :                 /* TODO: if /dev/urandom is available, PRNG is seeded
     929             :                  * automatically. If this is not the case, random data should
     930             :                  * be added here. */
     931             : 
     932             : #ifdef PKCS12_FUNCS
     933             : #ifndef OPENSSL_NO_RC2
     934             :                 /*
     935             :                  * 40-bit RC2 is commonly used in PKCS#12 files, so enable it.
     936             :                  * This is enabled by PKCS12_PBE_add() in OpenSSL 0.9.8
     937             :                  * versions, but it looks like OpenSSL 1.0.0 does not do that
     938             :                  * anymore.
     939             :                  */
     940         426 :                 EVP_add_cipher(EVP_rc2_40_cbc());
     941             : #endif /* OPENSSL_NO_RC2 */
     942         426 :                 PKCS12_PBE_add();
     943             : #endif  /* PKCS12_FUNCS */
     944             : #endif /* < 1.1.0 */
     945             :         } else {
     946        1142 :                 context = tls_context_new(conf);
     947        1142 :                 if (context == NULL)
     948           4 :                         return NULL;
     949             :         }
     950        1564 :         tls_openssl_ref_count++;
     951             : 
     952        1564 :         data = os_zalloc(sizeof(*data));
     953        1564 :         if (data)
     954        1560 :                 ssl = SSL_CTX_new(SSLv23_method());
     955             :         else
     956           4 :                 ssl = NULL;
     957        1564 :         if (ssl == NULL) {
     958           4 :                 tls_openssl_ref_count--;
     959           4 :                 if (context != tls_global)
     960           4 :                         os_free(context);
     961           4 :                 if (tls_openssl_ref_count == 0) {
     962           0 :                         os_free(tls_global);
     963           0 :                         tls_global = NULL;
     964             :                 }
     965           4 :                 os_free(data);
     966           4 :                 return NULL;
     967             :         }
     968        1560 :         data->ssl = ssl;
     969        1560 :         if (conf)
     970        1560 :                 data->tls_session_lifetime = conf->tls_session_lifetime;
     971             : 
     972        1560 :         SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv2);
     973        1560 :         SSL_CTX_set_options(ssl, SSL_OP_NO_SSLv3);
     974             : 
     975        1560 :         SSL_CTX_set_info_callback(ssl, ssl_info_cb);
     976        1560 :         SSL_CTX_set_app_data(ssl, context);
     977        1560 :         if (data->tls_session_lifetime > 0) {
     978          10 :                 SSL_CTX_set_quiet_shutdown(ssl, 1);
     979             :                 /*
     980             :                  * Set default context here. In practice, this will be replaced
     981             :                  * by the per-EAP method context in tls_connection_set_verify().
     982             :                  */
     983          10 :                 SSL_CTX_set_session_id_context(ssl, (u8 *) "hostapd", 7);
     984          10 :                 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_SERVER);
     985          10 :                 SSL_CTX_set_timeout(ssl, data->tls_session_lifetime);
     986          10 :                 SSL_CTX_sess_set_remove_cb(ssl, remove_session_cb);
     987             :         } else {
     988        1550 :                 SSL_CTX_set_session_cache_mode(ssl, SSL_SESS_CACHE_OFF);
     989             :         }
     990             : 
     991        1560 :         if (tls_ex_idx_session < 0) {
     992          48 :                 tls_ex_idx_session = SSL_SESSION_get_ex_new_index(
     993             :                         0, NULL, NULL, NULL, NULL);
     994          48 :                 if (tls_ex_idx_session < 0) {
     995           0 :                         tls_deinit(data);
     996           0 :                         return NULL;
     997             :                 }
     998             :         }
     999             : 
    1000             : #ifndef OPENSSL_NO_ENGINE
    1001             :         wpa_printf(MSG_DEBUG, "ENGINE: Loading dynamic engine");
    1002             :         ERR_load_ENGINE_strings();
    1003             :         ENGINE_load_dynamic();
    1004             : 
    1005             :         if (conf &&
    1006             :             (conf->opensc_engine_path || conf->pkcs11_engine_path ||
    1007             :              conf->pkcs11_module_path)) {
    1008             :                 if (tls_engine_load_dynamic_opensc(conf->opensc_engine_path) ||
    1009             :                     tls_engine_load_dynamic_pkcs11(conf->pkcs11_engine_path,
    1010             :                                                    conf->pkcs11_module_path)) {
    1011             :                         tls_deinit(data);
    1012             :                         return NULL;
    1013             :                 }
    1014             :         }
    1015             : #endif /* OPENSSL_NO_ENGINE */
    1016             : 
    1017        1560 :         if (conf && conf->openssl_ciphers)
    1018           0 :                 ciphers = conf->openssl_ciphers;
    1019             :         else
    1020        1560 :                 ciphers = "DEFAULT:!EXP:!LOW";
    1021        1560 :         if (SSL_CTX_set_cipher_list(ssl, ciphers) != 1) {
    1022           0 :                 wpa_printf(MSG_ERROR,
    1023             :                            "OpenSSL: Failed to set cipher string '%s'",
    1024             :                            ciphers);
    1025           0 :                 tls_deinit(data);
    1026           0 :                 return NULL;
    1027             :         }
    1028             : 
    1029        1560 :         return data;
    1030             : }
    1031             : 
    1032             : 
    1033        1560 : void tls_deinit(void *ssl_ctx)
    1034             : {
    1035        1560 :         struct tls_data *data = ssl_ctx;
    1036        1560 :         SSL_CTX *ssl = data->ssl;
    1037        1560 :         struct tls_context *context = SSL_CTX_get_app_data(ssl);
    1038        1560 :         if (context != tls_global)
    1039        1134 :                 os_free(context);
    1040        1560 :         if (data->tls_session_lifetime > 0)
    1041          10 :                 SSL_CTX_flush_sessions(ssl, 0);
    1042        1560 :         SSL_CTX_free(ssl);
    1043             : 
    1044        1560 :         tls_openssl_ref_count--;
    1045        1560 :         if (tls_openssl_ref_count == 0) {
    1046             : #if OPENSSL_VERSION_NUMBER < 0x10100000L
    1047             : #ifndef OPENSSL_NO_ENGINE
    1048             :                 ENGINE_cleanup();
    1049             : #endif /* OPENSSL_NO_ENGINE */
    1050         426 :                 CRYPTO_cleanup_all_ex_data();
    1051         426 :                 ERR_remove_thread_state(NULL);
    1052         426 :                 ERR_free_strings();
    1053         426 :                 EVP_cleanup();
    1054             : #endif /* < 1.1.0 */
    1055         426 :                 os_free(tls_global->ocsp_stapling_response);
    1056         426 :                 tls_global->ocsp_stapling_response = NULL;
    1057         426 :                 os_free(tls_global);
    1058         426 :                 tls_global = NULL;
    1059             :         }
    1060             : 
    1061        1560 :         os_free(data);
    1062        1560 : }
    1063             : 
    1064             : 
    1065             : #ifndef OPENSSL_NO_ENGINE
    1066             : 
    1067             : /* Cryptoki return values */
    1068             : #define CKR_PIN_INCORRECT 0x000000a0
    1069             : #define CKR_PIN_INVALID 0x000000a1
    1070             : #define CKR_PIN_LEN_RANGE 0x000000a2
    1071             : 
    1072             : /* libp11 */
    1073             : #define ERR_LIB_PKCS11  ERR_LIB_USER
    1074             : 
    1075             : static int tls_is_pin_error(unsigned int err)
    1076             : {
    1077             :         return ERR_GET_LIB(err) == ERR_LIB_PKCS11 &&
    1078             :                 (ERR_GET_REASON(err) == CKR_PIN_INCORRECT ||
    1079             :                  ERR_GET_REASON(err) == CKR_PIN_INVALID ||
    1080             :                  ERR_GET_REASON(err) == CKR_PIN_LEN_RANGE);
    1081             : }
    1082             : 
    1083             : #endif /* OPENSSL_NO_ENGINE */
    1084             : 
    1085             : 
    1086             : #ifdef ANDROID
    1087             : /* EVP_PKEY_from_keystore comes from system/security/keystore-engine. */
    1088             : EVP_PKEY * EVP_PKEY_from_keystore(const char *key_id);
    1089             : #endif /* ANDROID */
    1090             : 
    1091           0 : static int tls_engine_init(struct tls_connection *conn, const char *engine_id,
    1092             :                            const char *pin, const char *key_id,
    1093             :                            const char *cert_id, const char *ca_cert_id)
    1094             : {
    1095             : #if defined(ANDROID) && defined(OPENSSL_IS_BORINGSSL)
    1096             : #if !defined(OPENSSL_NO_ENGINE)
    1097             : #error "This code depends on OPENSSL_NO_ENGINE being defined by BoringSSL."
    1098             : #endif
    1099             :         if (!key_id)
    1100             :                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
    1101             :         conn->engine = NULL;
    1102             :         conn->private_key = EVP_PKEY_from_keystore(key_id);
    1103             :         if (!conn->private_key) {
    1104             :                 wpa_printf(MSG_ERROR,
    1105             :                            "ENGINE: cannot load private key with id '%s' [%s]",
    1106             :                            key_id,
    1107             :                            ERR_error_string(ERR_get_error(), NULL));
    1108             :                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
    1109             :         }
    1110             : #endif /* ANDROID && OPENSSL_IS_BORINGSSL */
    1111             : 
    1112             : #ifndef OPENSSL_NO_ENGINE
    1113             :         int ret = -1;
    1114             :         if (engine_id == NULL) {
    1115             :                 wpa_printf(MSG_ERROR, "ENGINE: Engine ID not set");
    1116             :                 return -1;
    1117             :         }
    1118             : 
    1119             :         ERR_clear_error();
    1120             : #ifdef ANDROID
    1121             :         ENGINE_load_dynamic();
    1122             : #endif
    1123             :         conn->engine = ENGINE_by_id(engine_id);
    1124             :         if (!conn->engine) {
    1125             :                 wpa_printf(MSG_ERROR, "ENGINE: engine %s not available [%s]",
    1126             :                            engine_id, ERR_error_string(ERR_get_error(), NULL));
    1127             :                 goto err;
    1128             :         }
    1129             :         if (ENGINE_init(conn->engine) != 1) {
    1130             :                 wpa_printf(MSG_ERROR, "ENGINE: engine init failed "
    1131             :                            "(engine: %s) [%s]", engine_id,
    1132             :                            ERR_error_string(ERR_get_error(), NULL));
    1133             :                 goto err;
    1134             :         }
    1135             :         wpa_printf(MSG_DEBUG, "ENGINE: engine initialized");
    1136             : 
    1137             : #ifndef ANDROID
    1138             :         if (pin && ENGINE_ctrl_cmd_string(conn->engine, "PIN", pin, 0) == 0) {
    1139             :                 wpa_printf(MSG_ERROR, "ENGINE: cannot set pin [%s]",
    1140             :                            ERR_error_string(ERR_get_error(), NULL));
    1141             :                 goto err;
    1142             :         }
    1143             : #endif
    1144             :         if (key_id) {
    1145             :                 /*
    1146             :                  * Ensure that the ENGINE does not attempt to use the OpenSSL
    1147             :                  * UI system to obtain a PIN, if we didn't provide one.
    1148             :                  */
    1149             :                 struct {
    1150             :                         const void *password;
    1151             :                         const char *prompt_info;
    1152             :                 } key_cb = { "", NULL };
    1153             : 
    1154             :                 /* load private key first in-case PIN is required for cert */
    1155             :                 conn->private_key = ENGINE_load_private_key(conn->engine,
    1156             :                                                             key_id, NULL,
    1157             :                                                             &key_cb);
    1158             :                 if (!conn->private_key) {
    1159             :                         unsigned long err = ERR_get_error();
    1160             : 
    1161             :                         wpa_printf(MSG_ERROR,
    1162             :                                    "ENGINE: cannot load private key with id '%s' [%s]",
    1163             :                                    key_id,
    1164             :                                    ERR_error_string(err, NULL));
    1165             :                         if (tls_is_pin_error(err))
    1166             :                                 ret = TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
    1167             :                         else
    1168             :                                 ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
    1169             :                         goto err;
    1170             :                 }
    1171             :         }
    1172             : 
    1173             :         /* handle a certificate and/or CA certificate */
    1174             :         if (cert_id || ca_cert_id) {
    1175             :                 const char *cmd_name = "LOAD_CERT_CTRL";
    1176             : 
    1177             :                 /* test if the engine supports a LOAD_CERT_CTRL */
    1178             :                 if (!ENGINE_ctrl(conn->engine, ENGINE_CTRL_GET_CMD_FROM_NAME,
    1179             :                                  0, (void *)cmd_name, NULL)) {
    1180             :                         wpa_printf(MSG_ERROR, "ENGINE: engine does not support"
    1181             :                                    " loading certificates");
    1182             :                         ret = TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
    1183             :                         goto err;
    1184             :                 }
    1185             :         }
    1186             : 
    1187             :         return 0;
    1188             : 
    1189             : err:
    1190             :         if (conn->engine) {
    1191             :                 ENGINE_free(conn->engine);
    1192             :                 conn->engine = NULL;
    1193             :         }
    1194             : 
    1195             :         if (conn->private_key) {
    1196             :                 EVP_PKEY_free(conn->private_key);
    1197             :                 conn->private_key = NULL;
    1198             :         }
    1199             : 
    1200             :         return ret;
    1201             : #else /* OPENSSL_NO_ENGINE */
    1202           0 :         return 0;
    1203             : #endif /* OPENSSL_NO_ENGINE */
    1204             : }
    1205             : 
    1206             : 
    1207        1531 : static void tls_engine_deinit(struct tls_connection *conn)
    1208             : {
    1209             : #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
    1210             :         wpa_printf(MSG_DEBUG, "ENGINE: engine deinit");
    1211             :         if (conn->private_key) {
    1212             :                 EVP_PKEY_free(conn->private_key);
    1213             :                 conn->private_key = NULL;
    1214             :         }
    1215             :         if (conn->engine) {
    1216             : #if !defined(OPENSSL_IS_BORINGSSL)
    1217             :                 ENGINE_finish(conn->engine);
    1218             : #endif /* !OPENSSL_IS_BORINGSSL */
    1219             :                 conn->engine = NULL;
    1220             :         }
    1221             : #endif /* ANDROID || !OPENSSL_NO_ENGINE */
    1222        1531 : }
    1223             : 
    1224             : 
    1225        4797 : int tls_get_errors(void *ssl_ctx)
    1226             : {
    1227        4797 :         int count = 0;
    1228             :         unsigned long err;
    1229             : 
    1230        9594 :         while ((err = ERR_get_error())) {
    1231           0 :                 wpa_printf(MSG_INFO, "TLS - SSL error: %s",
    1232             :                            ERR_error_string(err, NULL));
    1233           0 :                 count++;
    1234             :         }
    1235             : 
    1236        4797 :         return count;
    1237             : }
    1238             : 
    1239             : 
    1240       26713 : static const char * openssl_content_type(int content_type)
    1241             : {
    1242       26713 :         switch (content_type) {
    1243             :         case 20:
    1244        2140 :                 return "change cipher spec";
    1245             :         case 21:
    1246          67 :                 return "alert";
    1247             :         case 22:
    1248        8753 :                 return "handshake";
    1249             :         case 23:
    1250           0 :                 return "application data";
    1251             :         case 24:
    1252           0 :                 return "heartbeat";
    1253             :         case 256:
    1254       15753 :                 return "TLS header info"; /* pseudo content type */
    1255             :         default:
    1256           0 :                 return "?";
    1257             :         }
    1258             : }
    1259             : 
    1260             : 
    1261       26713 : static const char * openssl_handshake_type(int content_type, const u8 *buf,
    1262             :                                            size_t len)
    1263             : {
    1264       26713 :         if (content_type != 22 || !buf || len == 0)
    1265       17960 :                 return "";
    1266        8753 :         switch (buf[0]) {
    1267             :         case 0:
    1268           0 :                 return "hello request";
    1269             :         case 1:
    1270        1170 :                 return "client hello";
    1271             :         case 2:
    1272        1150 :                 return "server hello";
    1273             :         case 4:
    1274           0 :                 return "new session ticket";
    1275             :         case 11:
    1276        1066 :                 return "certificate";
    1277             :         case 12:
    1278        1015 :                 return "server key exchange";
    1279             :         case 13:
    1280         134 :                 return "certificate request";
    1281             :         case 14:
    1282         952 :                 return "server hello done";
    1283             :         case 15:
    1284         120 :                 return "certificate verify";
    1285             :         case 16:
    1286         980 :                 return "client key exchange";
    1287             :         case 20:
    1288        2140 :                 return "finished";
    1289             :         case 21:
    1290           0 :                 return "certificate url";
    1291             :         case 22:
    1292          26 :                 return "certificate status";
    1293             :         default:
    1294           0 :                 return "?";
    1295             :         }
    1296             : }
    1297             : 
    1298             : 
    1299       26713 : static void tls_msg_cb(int write_p, int version, int content_type,
    1300             :                        const void *buf, size_t len, SSL *ssl, void *arg)
    1301             : {
    1302       26713 :         struct tls_connection *conn = arg;
    1303       26713 :         const u8 *pos = buf;
    1304             : 
    1305       26713 :         if (write_p == 2) {
    1306           0 :                 wpa_printf(MSG_DEBUG,
    1307             :                            "OpenSSL: session ver=0x%x content_type=%d",
    1308             :                            version, content_type);
    1309           0 :                 wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Data", buf, len);
    1310       26713 :                 return;
    1311             :         }
    1312             : 
    1313       26713 :         wpa_printf(MSG_DEBUG, "OpenSSL: %s ver=0x%x content_type=%d (%s/%s)",
    1314             :                    write_p ? "TX" : "RX", version, content_type,
    1315             :                    openssl_content_type(content_type),
    1316             :                    openssl_handshake_type(content_type, buf, len));
    1317       26713 :         wpa_hexdump_key(MSG_MSGDUMP, "OpenSSL: Message", buf, len);
    1318       26713 :         if (content_type == 24 && len >= 3 && pos[0] == 1) {
    1319           0 :                 size_t payload_len = WPA_GET_BE16(pos + 1);
    1320           0 :                 if (payload_len + 3 > len) {
    1321           0 :                         wpa_printf(MSG_ERROR, "OpenSSL: Heartbeat attack detected");
    1322           0 :                         conn->invalid_hb_used = 1;
    1323             :                 }
    1324             :         }
    1325             : }
    1326             : 
    1327             : 
    1328        1537 : struct tls_connection * tls_connection_init(void *ssl_ctx)
    1329             : {
    1330        1537 :         struct tls_data *data = ssl_ctx;
    1331        1537 :         SSL_CTX *ssl = data->ssl;
    1332             :         struct tls_connection *conn;
    1333             :         long options;
    1334        1537 :         struct tls_context *context = SSL_CTX_get_app_data(ssl);
    1335             : 
    1336        1537 :         conn = os_zalloc(sizeof(*conn));
    1337        1537 :         if (conn == NULL)
    1338           6 :                 return NULL;
    1339        1531 :         conn->ssl_ctx = ssl;
    1340        1531 :         conn->ssl = SSL_new(ssl);
    1341        1531 :         if (conn->ssl == NULL) {
    1342           0 :                 tls_show_errors(MSG_INFO, __func__,
    1343             :                                 "Failed to initialize new SSL connection");
    1344           0 :                 os_free(conn);
    1345           0 :                 return NULL;
    1346             :         }
    1347             : 
    1348        1531 :         conn->context = context;
    1349        1531 :         SSL_set_app_data(conn->ssl, conn);
    1350        1531 :         SSL_set_msg_callback(conn->ssl, tls_msg_cb);
    1351        1531 :         SSL_set_msg_callback_arg(conn->ssl, conn);
    1352        1531 :         options = SSL_OP_NO_SSLv2 | SSL_OP_NO_SSLv3 |
    1353             :                 SSL_OP_SINGLE_DH_USE;
    1354             : #ifdef SSL_OP_NO_COMPRESSION
    1355        1531 :         options |= SSL_OP_NO_COMPRESSION;
    1356             : #endif /* SSL_OP_NO_COMPRESSION */
    1357        1531 :         SSL_set_options(conn->ssl, options);
    1358             : 
    1359        1531 :         conn->ssl_in = BIO_new(BIO_s_mem());
    1360        1531 :         if (!conn->ssl_in) {
    1361           0 :                 tls_show_errors(MSG_INFO, __func__,
    1362             :                                 "Failed to create a new BIO for ssl_in");
    1363           0 :                 SSL_free(conn->ssl);
    1364           0 :                 os_free(conn);
    1365           0 :                 return NULL;
    1366             :         }
    1367             : 
    1368        1531 :         conn->ssl_out = BIO_new(BIO_s_mem());
    1369        1531 :         if (!conn->ssl_out) {
    1370           0 :                 tls_show_errors(MSG_INFO, __func__,
    1371             :                                 "Failed to create a new BIO for ssl_out");
    1372           0 :                 SSL_free(conn->ssl);
    1373           0 :                 BIO_free(conn->ssl_in);
    1374           0 :                 os_free(conn);
    1375           0 :                 return NULL;
    1376             :         }
    1377             : 
    1378        1531 :         SSL_set_bio(conn->ssl, conn->ssl_in, conn->ssl_out);
    1379             : 
    1380        1531 :         return conn;
    1381             : }
    1382             : 
    1383             : 
    1384        1558 : void tls_connection_deinit(void *ssl_ctx, struct tls_connection *conn)
    1385             : {
    1386        1558 :         if (conn == NULL)
    1387        1585 :                 return;
    1388        1531 :         if (conn->success_data) {
    1389             :                 /*
    1390             :                  * Make sure ssl_clear_bad_session() does not remove this
    1391             :                  * session.
    1392             :                  */
    1393          21 :                 SSL_set_quiet_shutdown(conn->ssl, 1);
    1394          21 :                 SSL_shutdown(conn->ssl);
    1395             :         }
    1396        1531 :         SSL_free(conn->ssl);
    1397        1531 :         tls_engine_deinit(conn);
    1398        1531 :         os_free(conn->subject_match);
    1399        1531 :         os_free(conn->altsubject_match);
    1400        1531 :         os_free(conn->suffix_match);
    1401        1531 :         os_free(conn->domain_match);
    1402        1531 :         os_free(conn->session_ticket);
    1403        1531 :         os_free(conn);
    1404             : }
    1405             : 
    1406             : 
    1407       10149 : int tls_connection_established(void *ssl_ctx, struct tls_connection *conn)
    1408             : {
    1409       10149 :         return conn ? SSL_is_init_finished(conn->ssl) : 0;
    1410             : }
    1411             : 
    1412             : 
    1413          45 : int tls_connection_shutdown(void *ssl_ctx, struct tls_connection *conn)
    1414             : {
    1415          45 :         if (conn == NULL)
    1416           0 :                 return -1;
    1417             : 
    1418             :         /* Shutdown previous TLS connection without notifying the peer
    1419             :          * because the connection was already terminated in practice
    1420             :          * and "close notify" shutdown alert would confuse AS. */
    1421          45 :         SSL_set_quiet_shutdown(conn->ssl, 1);
    1422          45 :         SSL_shutdown(conn->ssl);
    1423          45 :         return SSL_clear(conn->ssl) == 1 ? 0 : -1;
    1424             : }
    1425             : 
    1426             : 
    1427          15 : static int tls_match_altsubject_component(X509 *cert, int type,
    1428             :                                           const char *value, size_t len)
    1429             : {
    1430             :         GENERAL_NAME *gen;
    1431             :         void *ext;
    1432          15 :         int found = 0;
    1433             :         stack_index_t i;
    1434             : 
    1435          15 :         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
    1436             : 
    1437          30 :         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
    1438          15 :                 gen = sk_GENERAL_NAME_value(ext, i);
    1439          15 :                 if (gen->type != type)
    1440           6 :                         continue;
    1441          14 :                 if (os_strlen((char *) gen->d.ia5->data) == len &&
    1442           5 :                     os_memcmp(value, gen->d.ia5->data, len) == 0)
    1443           5 :                         found++;
    1444             :         }
    1445             : 
    1446          15 :         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
    1447             : 
    1448          15 :         return found;
    1449             : }
    1450             : 
    1451             : 
    1452          10 : static int tls_match_altsubject(X509 *cert, const char *match)
    1453             : {
    1454             :         int type;
    1455             :         const char *pos, *end;
    1456             :         size_t len;
    1457             : 
    1458          10 :         pos = match;
    1459             :         do {
    1460          16 :                 if (os_strncmp(pos, "EMAIL:", 6) == 0) {
    1461           4 :                         type = GEN_EMAIL;
    1462           4 :                         pos += 6;
    1463          12 :                 } else if (os_strncmp(pos, "DNS:", 4) == 0) {
    1464           9 :                         type = GEN_DNS;
    1465           9 :                         pos += 4;
    1466           3 :                 } else if (os_strncmp(pos, "URI:", 4) == 0) {
    1467           2 :                         type = GEN_URI;
    1468           2 :                         pos += 4;
    1469             :                 } else {
    1470           1 :                         wpa_printf(MSG_INFO, "TLS: Invalid altSubjectName "
    1471             :                                    "match '%s'", pos);
    1472           1 :                         return 0;
    1473             :                 }
    1474          15 :                 end = os_strchr(pos, ';');
    1475          30 :                 while (end) {
    1476          16 :                         if (os_strncmp(end + 1, "EMAIL:", 6) == 0 ||
    1477          12 :                             os_strncmp(end + 1, "DNS:", 4) == 0 ||
    1478           4 :                             os_strncmp(end + 1, "URI:", 4) == 0)
    1479             :                                 break;
    1480           0 :                         end = os_strchr(end + 1, ';');
    1481             :                 }
    1482          15 :                 if (end)
    1483           8 :                         len = end - pos;
    1484             :                 else
    1485           7 :                         len = os_strlen(pos);
    1486          15 :                 if (tls_match_altsubject_component(cert, type, pos, len) > 0)
    1487           5 :                         return 1;
    1488          10 :                 pos = end + 1;
    1489          10 :         } while (end);
    1490             : 
    1491           4 :         return 0;
    1492             : }
    1493             : 
    1494             : 
    1495             : #ifndef CONFIG_NATIVE_WINDOWS
    1496          22 : static int domain_suffix_match(const u8 *val, size_t len, const char *match,
    1497             :                                int full)
    1498             : {
    1499             :         size_t i, match_len;
    1500             : 
    1501             :         /* Check for embedded nuls that could mess up suffix matching */
    1502         293 :         for (i = 0; i < len; i++) {
    1503         271 :                 if (val[i] == '\0') {
    1504           0 :                         wpa_printf(MSG_DEBUG, "TLS: Embedded null in a string - reject");
    1505           0 :                         return 0;
    1506             :                 }
    1507             :         }
    1508             : 
    1509          22 :         match_len = os_strlen(match);
    1510          22 :         if (match_len > len || (full && match_len != len))
    1511           5 :                 return 0;
    1512             : 
    1513          17 :         if (os_strncasecmp((const char *) val + len - match_len, match,
    1514             :                            match_len) != 0)
    1515           1 :                 return 0; /* no match */
    1516             : 
    1517          16 :         if (match_len == len)
    1518          11 :                 return 1; /* exact match */
    1519             : 
    1520           5 :         if (val[len - match_len - 1] == '.')
    1521           4 :                 return 1; /* full label match completes suffix match */
    1522             : 
    1523           1 :         wpa_printf(MSG_DEBUG, "TLS: Reject due to incomplete label match");
    1524           1 :         return 0;
    1525             : }
    1526             : #endif /* CONFIG_NATIVE_WINDOWS */
    1527             : 
    1528             : 
    1529          22 : static int tls_match_suffix(X509 *cert, const char *match, int full)
    1530             : {
    1531             : #ifdef CONFIG_NATIVE_WINDOWS
    1532             :         /* wincrypt.h has conflicting X509_NAME definition */
    1533             :         return -1;
    1534             : #else /* CONFIG_NATIVE_WINDOWS */
    1535             :         GENERAL_NAME *gen;
    1536             :         void *ext;
    1537             :         int i;
    1538             :         stack_index_t j;
    1539          22 :         int dns_name = 0;
    1540             :         X509_NAME *name;
    1541             : 
    1542          22 :         wpa_printf(MSG_DEBUG, "TLS: Match domain against %s%s",
    1543             :                    full ? "": "suffix ", match);
    1544             : 
    1545          22 :         ext = X509_get_ext_d2i(cert, NID_subject_alt_name, NULL, NULL);
    1546             : 
    1547          25 :         for (j = 0; ext && j < sk_GENERAL_NAME_num(ext); j++) {
    1548          15 :                 gen = sk_GENERAL_NAME_value(ext, j);
    1549          15 :                 if (gen->type != GEN_DNS)
    1550           0 :                         continue;
    1551          15 :                 dns_name++;
    1552          30 :                 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate dNSName",
    1553          15 :                                   gen->d.dNSName->data,
    1554          15 :                                   gen->d.dNSName->length);
    1555          15 :                 if (domain_suffix_match(gen->d.dNSName->data,
    1556          15 :                                         gen->d.dNSName->length, match, full) ==
    1557             :                     1) {
    1558          12 :                         wpa_printf(MSG_DEBUG, "TLS: %s in dNSName found",
    1559             :                                    full ? "Match" : "Suffix match");
    1560          12 :                         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
    1561          12 :                         return 1;
    1562             :                 }
    1563             :         }
    1564          10 :         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
    1565             : 
    1566          10 :         if (dns_name) {
    1567           3 :                 wpa_printf(MSG_DEBUG, "TLS: None of the dNSName(s) matched");
    1568           3 :                 return 0;
    1569             :         }
    1570             : 
    1571           7 :         name = X509_get_subject_name(cert);
    1572           7 :         i = -1;
    1573             :         for (;;) {
    1574             :                 X509_NAME_ENTRY *e;
    1575             :                 ASN1_STRING *cn;
    1576             : 
    1577          11 :                 i = X509_NAME_get_index_by_NID(name, NID_commonName, i);
    1578          11 :                 if (i == -1)
    1579           4 :                         break;
    1580           7 :                 e = X509_NAME_get_entry(name, i);
    1581           7 :                 if (e == NULL)
    1582           0 :                         continue;
    1583           7 :                 cn = X509_NAME_ENTRY_get_data(e);
    1584           7 :                 if (cn == NULL)
    1585           0 :                         continue;
    1586          14 :                 wpa_hexdump_ascii(MSG_DEBUG, "TLS: Certificate commonName",
    1587          14 :                                   cn->data, cn->length);
    1588           7 :                 if (domain_suffix_match(cn->data, cn->length, match, full) == 1)
    1589             :                 {
    1590           3 :                         wpa_printf(MSG_DEBUG, "TLS: %s in commonName found",
    1591             :                                    full ? "Match" : "Suffix match");
    1592           3 :                         return 1;
    1593             :                 }
    1594           4 :         }
    1595             : 
    1596           4 :         wpa_printf(MSG_DEBUG, "TLS: No CommonName %smatch found",
    1597             :                    full ? "": "suffix ");
    1598           4 :         return 0;
    1599             : #endif /* CONFIG_NATIVE_WINDOWS */
    1600             : }
    1601             : 
    1602             : 
    1603           8 : static enum tls_fail_reason openssl_tls_fail_reason(int err)
    1604             : {
    1605           8 :         switch (err) {
    1606             :         case X509_V_ERR_CERT_REVOKED:
    1607           0 :                 return TLS_FAIL_REVOKED;
    1608             :         case X509_V_ERR_CERT_NOT_YET_VALID:
    1609             :         case X509_V_ERR_CRL_NOT_YET_VALID:
    1610           0 :                 return TLS_FAIL_NOT_YET_VALID;
    1611             :         case X509_V_ERR_CERT_HAS_EXPIRED:
    1612             :         case X509_V_ERR_CRL_HAS_EXPIRED:
    1613           1 :                 return TLS_FAIL_EXPIRED;
    1614             :         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT:
    1615             :         case X509_V_ERR_UNABLE_TO_GET_CRL:
    1616             :         case X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER:
    1617             :         case X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN:
    1618             :         case X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY:
    1619             :         case X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT:
    1620             :         case X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE:
    1621             :         case X509_V_ERR_CERT_CHAIN_TOO_LONG:
    1622             :         case X509_V_ERR_PATH_LENGTH_EXCEEDED:
    1623             :         case X509_V_ERR_INVALID_CA:
    1624           6 :                 return TLS_FAIL_UNTRUSTED;
    1625             :         case X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE:
    1626             :         case X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE:
    1627             :         case X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY:
    1628             :         case X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD:
    1629             :         case X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD:
    1630             :         case X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD:
    1631             :         case X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD:
    1632             :         case X509_V_ERR_CERT_UNTRUSTED:
    1633             :         case X509_V_ERR_CERT_REJECTED:
    1634           0 :                 return TLS_FAIL_BAD_CERTIFICATE;
    1635             :         default:
    1636           1 :                 return TLS_FAIL_UNSPECIFIED;
    1637             :         }
    1638             : }
    1639             : 
    1640             : 
    1641         965 : static struct wpabuf * get_x509_cert(X509 *cert)
    1642             : {
    1643             :         struct wpabuf *buf;
    1644             :         u8 *tmp;
    1645             : 
    1646         965 :         int cert_len = i2d_X509(cert, NULL);
    1647         965 :         if (cert_len <= 0)
    1648           0 :                 return NULL;
    1649             : 
    1650         965 :         buf = wpabuf_alloc(cert_len);
    1651         965 :         if (buf == NULL)
    1652           0 :                 return NULL;
    1653             : 
    1654         965 :         tmp = wpabuf_put(buf, cert_len);
    1655         965 :         i2d_X509(cert, &tmp);
    1656         965 :         return buf;
    1657             : }
    1658             : 
    1659             : 
    1660          23 : static void openssl_tls_fail_event(struct tls_connection *conn,
    1661             :                                    X509 *err_cert, int err, int depth,
    1662             :                                    const char *subject, const char *err_str,
    1663             :                                    enum tls_fail_reason reason)
    1664             : {
    1665             :         union tls_event_data ev;
    1666          23 :         struct wpabuf *cert = NULL;
    1667          23 :         struct tls_context *context = conn->context;
    1668             : 
    1669          23 :         if (context->event_cb == NULL)
    1670          24 :                 return;
    1671             : 
    1672          22 :         cert = get_x509_cert(err_cert);
    1673          22 :         os_memset(&ev, 0, sizeof(ev));
    1674          22 :         ev.cert_fail.reason = reason != TLS_FAIL_UNSPECIFIED ?
    1675             :                 reason : openssl_tls_fail_reason(err);
    1676          22 :         ev.cert_fail.depth = depth;
    1677          22 :         ev.cert_fail.subject = subject;
    1678          22 :         ev.cert_fail.reason_txt = err_str;
    1679          22 :         ev.cert_fail.cert = cert;
    1680          22 :         context->event_cb(context->cb_ctx, TLS_CERT_CHAIN_FAILURE, &ev);
    1681          22 :         wpabuf_free(cert);
    1682             : }
    1683             : 
    1684             : 
    1685        1061 : static void openssl_tls_cert_event(struct tls_connection *conn,
    1686             :                                    X509 *err_cert, int depth,
    1687             :                                    const char *subject)
    1688             : {
    1689        1061 :         struct wpabuf *cert = NULL;
    1690             :         union tls_event_data ev;
    1691        1061 :         struct tls_context *context = conn->context;
    1692             :         char *altsubject[TLS_MAX_ALT_SUBJECT];
    1693        1061 :         int alt, num_altsubject = 0;
    1694             :         GENERAL_NAME *gen;
    1695             :         void *ext;
    1696             :         stack_index_t i;
    1697             : #ifdef CONFIG_SHA256
    1698             :         u8 hash[32];
    1699             : #endif /* CONFIG_SHA256 */
    1700             : 
    1701        1061 :         if (context->event_cb == NULL)
    1702        1181 :                 return;
    1703             : 
    1704         941 :         os_memset(&ev, 0, sizeof(ev));
    1705        1861 :         if (conn->cert_probe || (conn->flags & TLS_CONN_EXT_CERT_CHECK) ||
    1706         920 :             context->cert_in_cb) {
    1707         941 :                 cert = get_x509_cert(err_cert);
    1708         941 :                 ev.peer_cert.cert = cert;
    1709             :         }
    1710             : #ifdef CONFIG_SHA256
    1711         941 :         if (cert) {
    1712             :                 const u8 *addr[1];
    1713             :                 size_t len[1];
    1714         941 :                 addr[0] = wpabuf_head(cert);
    1715         941 :                 len[0] = wpabuf_len(cert);
    1716         941 :                 if (sha256_vector(1, addr, len, hash) == 0) {
    1717         941 :                         ev.peer_cert.hash = hash;
    1718         941 :                         ev.peer_cert.hash_len = sizeof(hash);
    1719             :                 }
    1720             :         }
    1721             : #endif /* CONFIG_SHA256 */
    1722         941 :         ev.peer_cert.depth = depth;
    1723         941 :         ev.peer_cert.subject = subject;
    1724             : 
    1725         941 :         ext = X509_get_ext_d2i(err_cert, NID_subject_alt_name, NULL, NULL);
    1726        1383 :         for (i = 0; ext && i < sk_GENERAL_NAME_num(ext); i++) {
    1727             :                 char *pos;
    1728             : 
    1729         442 :                 if (num_altsubject == TLS_MAX_ALT_SUBJECT)
    1730           0 :                         break;
    1731         442 :                 gen = sk_GENERAL_NAME_value(ext, i);
    1732         884 :                 if (gen->type != GEN_EMAIL &&
    1733         442 :                     gen->type != GEN_DNS &&
    1734           0 :                     gen->type != GEN_URI)
    1735           0 :                         continue;
    1736             : 
    1737         442 :                 pos = os_malloc(10 + gen->d.ia5->length + 1);
    1738         442 :                 if (pos == NULL)
    1739           0 :                         break;
    1740         442 :                 altsubject[num_altsubject++] = pos;
    1741             : 
    1742         442 :                 switch (gen->type) {
    1743             :                 case GEN_EMAIL:
    1744           0 :                         os_memcpy(pos, "EMAIL:", 6);
    1745           0 :                         pos += 6;
    1746           0 :                         break;
    1747             :                 case GEN_DNS:
    1748         442 :                         os_memcpy(pos, "DNS:", 4);
    1749         442 :                         pos += 4;
    1750         442 :                         break;
    1751             :                 case GEN_URI:
    1752           0 :                         os_memcpy(pos, "URI:", 4);
    1753           0 :                         pos += 4;
    1754           0 :                         break;
    1755             :                 }
    1756             : 
    1757         442 :                 os_memcpy(pos, gen->d.ia5->data, gen->d.ia5->length);
    1758         442 :                 pos += gen->d.ia5->length;
    1759         442 :                 *pos = '\0';
    1760             :         }
    1761         941 :         sk_GENERAL_NAME_pop_free(ext, GENERAL_NAME_free);
    1762             : 
    1763        1383 :         for (alt = 0; alt < num_altsubject; alt++)
    1764         442 :                 ev.peer_cert.altsubject[alt] = altsubject[alt];
    1765         941 :         ev.peer_cert.num_altsubject = num_altsubject;
    1766             : 
    1767         941 :         context->event_cb(context->cb_ctx, TLS_PEER_CERTIFICATE, &ev);
    1768         941 :         wpabuf_free(cert);
    1769        1383 :         for (alt = 0; alt < num_altsubject; alt++)
    1770         442 :                 os_free(altsubject[alt]);
    1771             : }
    1772             : 
    1773             : 
    1774        1083 : static int tls_verify_cb(int preverify_ok, X509_STORE_CTX *x509_ctx)
    1775             : {
    1776             :         char buf[256];
    1777             :         X509 *err_cert;
    1778             :         int err, depth;
    1779             :         SSL *ssl;
    1780             :         struct tls_connection *conn;
    1781             :         struct tls_context *context;
    1782             :         char *match, *altmatch, *suffix_match, *domain_match;
    1783             :         const char *err_str;
    1784             : 
    1785        1083 :         err_cert = X509_STORE_CTX_get_current_cert(x509_ctx);
    1786        1083 :         if (!err_cert)
    1787           0 :                 return 0;
    1788             : 
    1789        1083 :         err = X509_STORE_CTX_get_error(x509_ctx);
    1790        1083 :         depth = X509_STORE_CTX_get_error_depth(x509_ctx);
    1791        1083 :         ssl = X509_STORE_CTX_get_ex_data(x509_ctx,
    1792             :                                          SSL_get_ex_data_X509_STORE_CTX_idx());
    1793        1083 :         X509_NAME_oneline(X509_get_subject_name(err_cert), buf, sizeof(buf));
    1794             : 
    1795        1083 :         conn = SSL_get_app_data(ssl);
    1796        1083 :         if (conn == NULL)
    1797           0 :                 return 0;
    1798             : 
    1799        1083 :         if (depth == 0)
    1800         525 :                 conn->peer_cert = err_cert;
    1801         558 :         else if (depth == 1)
    1802         553 :                 conn->peer_issuer = err_cert;
    1803           5 :         else if (depth == 2)
    1804           5 :                 conn->peer_issuer_issuer = err_cert;
    1805             : 
    1806        1083 :         context = conn->context;
    1807        1083 :         match = conn->subject_match;
    1808        1083 :         altmatch = conn->altsubject_match;
    1809        1083 :         suffix_match = conn->suffix_match;
    1810        1083 :         domain_match = conn->domain_match;
    1811             : 
    1812        1083 :         if (!preverify_ok && !conn->ca_cert_verify)
    1813          24 :                 preverify_ok = 1;
    1814        1083 :         if (!preverify_ok && depth > 0 && conn->server_cert_only)
    1815           2 :                 preverify_ok = 1;
    1816        1083 :         if (!preverify_ok && (conn->flags & TLS_CONN_DISABLE_TIME_CHECKS) &&
    1817           0 :             (err == X509_V_ERR_CERT_HAS_EXPIRED ||
    1818             :              err == X509_V_ERR_CERT_NOT_YET_VALID)) {
    1819           1 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Ignore certificate validity "
    1820             :                            "time mismatch");
    1821           1 :                 preverify_ok = 1;
    1822             :         }
    1823             : 
    1824        1083 :         err_str = X509_verify_cert_error_string(err);
    1825             : 
    1826             : #ifdef CONFIG_SHA256
    1827             :         /*
    1828             :          * Do not require preverify_ok so we can explicity allow otherwise
    1829             :          * invalid pinned server certificates.
    1830             :          */
    1831        1083 :         if (depth == 0 && conn->server_cert_only) {
    1832             :                 struct wpabuf *cert;
    1833           2 :                 cert = get_x509_cert(err_cert);
    1834           2 :                 if (!cert) {
    1835           0 :                         wpa_printf(MSG_DEBUG, "OpenSSL: Could not fetch "
    1836             :                                    "server certificate data");
    1837           0 :                         preverify_ok = 0;
    1838             :                 } else {
    1839             :                         u8 hash[32];
    1840             :                         const u8 *addr[1];
    1841             :                         size_t len[1];
    1842           2 :                         addr[0] = wpabuf_head(cert);
    1843           2 :                         len[0] = wpabuf_len(cert);
    1844           4 :                         if (sha256_vector(1, addr, len, hash) < 0 ||
    1845           2 :                             os_memcmp(conn->srv_cert_hash, hash, 32) != 0) {
    1846           1 :                                 err_str = "Server certificate mismatch";
    1847           1 :                                 err = X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN;
    1848           1 :                                 preverify_ok = 0;
    1849           1 :                         } else if (!preverify_ok) {
    1850             :                                 /*
    1851             :                                  * Certificate matches pinned certificate, allow
    1852             :                                  * regardless of other problems.
    1853             :                                  */
    1854           0 :                                 wpa_printf(MSG_DEBUG,
    1855             :                                            "OpenSSL: Ignore validation issues for a pinned server certificate");
    1856           0 :                                 preverify_ok = 1;
    1857             :                         }
    1858           2 :                         wpabuf_free(cert);
    1859             :                 }
    1860             :         }
    1861             : #endif /* CONFIG_SHA256 */
    1862             : 
    1863        1083 :         if (!preverify_ok) {
    1864           9 :                 wpa_printf(MSG_WARNING, "TLS: Certificate verification failed,"
    1865             :                            " error %d (%s) depth %d for '%s'", err, err_str,
    1866             :                            depth, buf);
    1867           9 :                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1868             :                                        err_str, TLS_FAIL_UNSPECIFIED);
    1869           9 :                 return preverify_ok;
    1870             :         }
    1871             : 
    1872        1074 :         wpa_printf(MSG_DEBUG, "TLS: tls_verify_cb - preverify_ok=%d "
    1873             :                    "err=%d (%s) ca_cert_verify=%d depth=%d buf='%s'",
    1874             :                    preverify_ok, err, err_str,
    1875        1074 :                    conn->ca_cert_verify, depth, buf);
    1876        1074 :         if (depth == 0 && match && os_strstr(buf, match) == NULL) {
    1877           1 :                 wpa_printf(MSG_WARNING, "TLS: Subject '%s' did not "
    1878             :                            "match with '%s'", buf, match);
    1879           1 :                 preverify_ok = 0;
    1880           1 :                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1881             :                                        "Subject mismatch",
    1882             :                                        TLS_FAIL_SUBJECT_MISMATCH);
    1883        1083 :         } else if (depth == 0 && altmatch &&
    1884          10 :                    !tls_match_altsubject(err_cert, altmatch)) {
    1885           5 :                 wpa_printf(MSG_WARNING, "TLS: altSubjectName match "
    1886             :                            "'%s' not found", altmatch);
    1887           5 :                 preverify_ok = 0;
    1888           5 :                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1889             :                                        "AltSubject mismatch",
    1890             :                                        TLS_FAIL_ALTSUBJECT_MISMATCH);
    1891        1084 :         } else if (depth == 0 && suffix_match &&
    1892          16 :                    !tls_match_suffix(err_cert, suffix_match, 0)) {
    1893           4 :                 wpa_printf(MSG_WARNING, "TLS: Domain suffix match '%s' not found",
    1894             :                            suffix_match);
    1895           4 :                 preverify_ok = 0;
    1896           4 :                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1897             :                                        "Domain suffix mismatch",
    1898             :                                        TLS_FAIL_DOMAIN_SUFFIX_MISMATCH);
    1899        1070 :         } else if (depth == 0 && domain_match &&
    1900           6 :                    !tls_match_suffix(err_cert, domain_match, 1)) {
    1901           3 :                 wpa_printf(MSG_WARNING, "TLS: Domain match '%s' not found",
    1902             :                            domain_match);
    1903           3 :                 preverify_ok = 0;
    1904           3 :                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1905             :                                        "Domain mismatch",
    1906             :                                        TLS_FAIL_DOMAIN_MISMATCH);
    1907             :         } else
    1908        1061 :                 openssl_tls_cert_event(conn, err_cert, depth, buf);
    1909             : 
    1910        1074 :         if (conn->cert_probe && preverify_ok && depth == 0) {
    1911           1 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Reject server certificate "
    1912             :                            "on probe-only run");
    1913           1 :                 preverify_ok = 0;
    1914           1 :                 openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1915             :                                        "Server certificate chain probe",
    1916             :                                        TLS_FAIL_SERVER_CHAIN_PROBE);
    1917             :         }
    1918             : 
    1919             : #ifdef OPENSSL_IS_BORINGSSL
    1920             :         if (depth == 0 && (conn->flags & TLS_CONN_REQUEST_OCSP) &&
    1921             :             preverify_ok) {
    1922             :                 enum ocsp_result res;
    1923             : 
    1924             :                 res = check_ocsp_resp(conn->ssl_ctx, conn->ssl, err_cert,
    1925             :                                       conn->peer_issuer,
    1926             :                                       conn->peer_issuer_issuer);
    1927             :                 if (res == OCSP_REVOKED) {
    1928             :                         preverify_ok = 0;
    1929             :                         openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1930             :                                                "certificate revoked",
    1931             :                                                TLS_FAIL_REVOKED);
    1932             :                         if (err == X509_V_OK)
    1933             :                                 X509_STORE_CTX_set_error(
    1934             :                                         x509_ctx, X509_V_ERR_CERT_REVOKED);
    1935             :                 } else if (res != OCSP_GOOD &&
    1936             :                            (conn->flags & TLS_CONN_REQUIRE_OCSP)) {
    1937             :                         preverify_ok = 0;
    1938             :                         openssl_tls_fail_event(conn, err_cert, err, depth, buf,
    1939             :                                                "bad certificate status response",
    1940             :                                                TLS_FAIL_UNSPECIFIED);
    1941             :                 }
    1942             :         }
    1943             : #endif /* OPENSSL_IS_BORINGSSL */
    1944             : 
    1945        1074 :         if (depth == 0 && preverify_ok && context->event_cb != NULL)
    1946         448 :                 context->event_cb(context->cb_ctx,
    1947             :                                   TLS_CERT_CHAIN_SUCCESS, NULL);
    1948             : 
    1949        1074 :         return preverify_ok;
    1950             : }
    1951             : 
    1952             : 
    1953             : #ifndef OPENSSL_NO_STDIO
    1954           8 : static int tls_load_ca_der(struct tls_data *data, const char *ca_cert)
    1955             : {
    1956           8 :         SSL_CTX *ssl_ctx = data->ssl;
    1957             :         X509_LOOKUP *lookup;
    1958           8 :         int ret = 0;
    1959             : 
    1960           8 :         lookup = X509_STORE_add_lookup(SSL_CTX_get_cert_store(ssl_ctx),
    1961             :                                        X509_LOOKUP_file());
    1962           8 :         if (lookup == NULL) {
    1963           0 :                 tls_show_errors(MSG_WARNING, __func__,
    1964             :                                 "Failed add lookup for X509 store");
    1965           0 :                 return -1;
    1966             :         }
    1967             : 
    1968           8 :         if (!X509_LOOKUP_load_file(lookup, ca_cert, X509_FILETYPE_ASN1)) {
    1969           0 :                 unsigned long err = ERR_peek_error();
    1970           0 :                 tls_show_errors(MSG_WARNING, __func__,
    1971             :                                 "Failed load CA in DER format");
    1972           0 :                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
    1973           0 :                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
    1974           0 :                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
    1975             :                                    "cert already in hash table error",
    1976             :                                    __func__);
    1977             :                 } else
    1978           0 :                         ret = -1;
    1979             :         }
    1980             : 
    1981           8 :         return ret;
    1982             : }
    1983             : #endif /* OPENSSL_NO_STDIO */
    1984             : 
    1985             : 
    1986         598 : static int tls_connection_ca_cert(struct tls_data *data,
    1987             :                                   struct tls_connection *conn,
    1988             :                                   const char *ca_cert, const u8 *ca_cert_blob,
    1989             :                                   size_t ca_cert_blob_len, const char *ca_path)
    1990             : {
    1991         598 :         SSL_CTX *ssl_ctx = data->ssl;
    1992             :         X509_STORE *store;
    1993             : 
    1994             :         /*
    1995             :          * Remove previously configured trusted CA certificates before adding
    1996             :          * new ones.
    1997             :          */
    1998         598 :         store = X509_STORE_new();
    1999         598 :         if (store == NULL) {
    2000           0 :                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
    2001             :                            "certificate store", __func__);
    2002           0 :                 return -1;
    2003             :         }
    2004         598 :         SSL_CTX_set_cert_store(ssl_ctx, store);
    2005             : 
    2006         598 :         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
    2007         598 :         conn->ca_cert_verify = 1;
    2008             : 
    2009         598 :         if (ca_cert && os_strncmp(ca_cert, "probe://", 8) == 0) {
    2010           1 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Probe for server certificate "
    2011             :                            "chain");
    2012           1 :                 conn->cert_probe = 1;
    2013           1 :                 conn->ca_cert_verify = 0;
    2014           1 :                 return 0;
    2015             :         }
    2016             : 
    2017         597 :         if (ca_cert && os_strncmp(ca_cert, "hash://", 7) == 0) {
    2018             : #ifdef CONFIG_SHA256
    2019           5 :                 const char *pos = ca_cert + 7;
    2020           5 :                 if (os_strncmp(pos, "server/sha256/", 14) != 0) {
    2021           1 :                         wpa_printf(MSG_DEBUG, "OpenSSL: Unsupported ca_cert "
    2022             :                                    "hash value '%s'", ca_cert);
    2023           1 :                         return -1;
    2024             :                 }
    2025           4 :                 pos += 14;
    2026           4 :                 if (os_strlen(pos) != 32 * 2) {
    2027           1 :                         wpa_printf(MSG_DEBUG, "OpenSSL: Unexpected SHA256 "
    2028             :                                    "hash length in ca_cert '%s'", ca_cert);
    2029           1 :                         return -1;
    2030             :                 }
    2031           3 :                 if (hexstr2bin(pos, conn->srv_cert_hash, 32) < 0) {
    2032           1 :                         wpa_printf(MSG_DEBUG, "OpenSSL: Invalid SHA256 hash "
    2033             :                                    "value in ca_cert '%s'", ca_cert);
    2034           1 :                         return -1;
    2035             :                 }
    2036           2 :                 conn->server_cert_only = 1;
    2037           2 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Checking only server "
    2038             :                            "certificate match");
    2039           2 :                 return 0;
    2040             : #else /* CONFIG_SHA256 */
    2041             :                 wpa_printf(MSG_INFO, "No SHA256 included in the build - "
    2042             :                            "cannot validate server certificate hash");
    2043             :                 return -1;
    2044             : #endif /* CONFIG_SHA256 */
    2045             :         }
    2046             : 
    2047         592 :         if (ca_cert_blob) {
    2048           3 :                 X509 *cert = d2i_X509(NULL,
    2049             :                                       (const unsigned char **) &ca_cert_blob,
    2050             :                                       ca_cert_blob_len);
    2051           3 :                 if (cert == NULL) {
    2052           0 :                         tls_show_errors(MSG_WARNING, __func__,
    2053             :                                         "Failed to parse ca_cert_blob");
    2054           0 :                         return -1;
    2055             :                 }
    2056             : 
    2057           3 :                 if (!X509_STORE_add_cert(SSL_CTX_get_cert_store(ssl_ctx),
    2058             :                                          cert)) {
    2059           0 :                         unsigned long err = ERR_peek_error();
    2060           0 :                         tls_show_errors(MSG_WARNING, __func__,
    2061             :                                         "Failed to add ca_cert_blob to "
    2062             :                                         "certificate store");
    2063           0 :                         if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
    2064           0 :                             ERR_GET_REASON(err) ==
    2065             :                             X509_R_CERT_ALREADY_IN_HASH_TABLE) {
    2066           0 :                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring "
    2067             :                                            "cert already in hash table error",
    2068             :                                            __func__);
    2069             :                         } else {
    2070           0 :                                 X509_free(cert);
    2071           0 :                                 return -1;
    2072             :                         }
    2073             :                 }
    2074           3 :                 X509_free(cert);
    2075           3 :                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - added ca_cert_blob "
    2076             :                            "to certificate store", __func__);
    2077           3 :                 return 0;
    2078             :         }
    2079             : 
    2080             : #ifdef ANDROID
    2081             :         /* Single alias */
    2082             :         if (ca_cert && os_strncmp("keystore://", ca_cert, 11) == 0) {
    2083             :                 if (tls_add_ca_from_keystore(SSL_CTX_get_cert_store(ssl_ctx),
    2084             :                                              &ca_cert[11]) < 0)
    2085             :                         return -1;
    2086             :                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
    2087             :                 return 0;
    2088             :         }
    2089             : 
    2090             :         /* Multiple aliases separated by space */
    2091             :         if (ca_cert && os_strncmp("keystores://", ca_cert, 12) == 0) {
    2092             :                 char *aliases = os_strdup(&ca_cert[12]);
    2093             :                 const char *delim = " ";
    2094             :                 int rc = 0;
    2095             :                 char *savedptr;
    2096             :                 char *alias;
    2097             : 
    2098             :                 if (!aliases)
    2099             :                         return -1;
    2100             :                 alias = strtok_r(aliases, delim, &savedptr);
    2101             :                 for (; alias; alias = strtok_r(NULL, delim, &savedptr)) {
    2102             :                         if (tls_add_ca_from_keystore_encoded(
    2103             :                                     SSL_CTX_get_cert_store(ssl_ctx), alias)) {
    2104             :                                 wpa_printf(MSG_WARNING,
    2105             :                                            "OpenSSL: %s - Failed to add ca_cert %s from keystore",
    2106             :                                            __func__, alias);
    2107             :                                 rc = -1;
    2108             :                                 break;
    2109             :                         }
    2110             :                 }
    2111             :                 os_free(aliases);
    2112             :                 if (rc)
    2113             :                         return rc;
    2114             : 
    2115             :                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
    2116             :                 return 0;
    2117             :         }
    2118             : #endif /* ANDROID */
    2119             : 
    2120             : #ifdef CONFIG_NATIVE_WINDOWS
    2121             :         if (ca_cert && tls_cryptoapi_ca_cert(ssl_ctx, conn->ssl, ca_cert) ==
    2122             :             0) {
    2123             :                 wpa_printf(MSG_DEBUG, "OpenSSL: Added CA certificates from "
    2124             :                            "system certificate store");
    2125             :                 return 0;
    2126             :         }
    2127             : #endif /* CONFIG_NATIVE_WINDOWS */
    2128             : 
    2129         589 :         if (ca_cert || ca_path) {
    2130             : #ifndef OPENSSL_NO_STDIO
    2131        1130 :                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, ca_path) !=
    2132             :                     1) {
    2133           8 :                         tls_show_errors(MSG_WARNING, __func__,
    2134             :                                         "Failed to load root certificates");
    2135          16 :                         if (ca_cert &&
    2136           8 :                             tls_load_ca_der(data, ca_cert) == 0) {
    2137           8 :                                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - loaded "
    2138             :                                            "DER format CA certificate",
    2139             :                                            __func__);
    2140             :                         } else
    2141           0 :                                 return -1;
    2142             :                 } else {
    2143         557 :                         wpa_printf(MSG_DEBUG, "TLS: Trusted root "
    2144             :                                    "certificate(s) loaded");
    2145         557 :                         tls_get_errors(data);
    2146             :                 }
    2147             : #else /* OPENSSL_NO_STDIO */
    2148             :                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
    2149             :                            __func__);
    2150             :                 return -1;
    2151             : #endif /* OPENSSL_NO_STDIO */
    2152             :         } else {
    2153             :                 /* No ca_cert configured - do not try to verify server
    2154             :                  * certificate */
    2155          24 :                 conn->ca_cert_verify = 0;
    2156             :         }
    2157             : 
    2158         589 :         return 0;
    2159             : }
    2160             : 
    2161             : 
    2162         130 : static int tls_global_ca_cert(struct tls_data *data, const char *ca_cert)
    2163             : {
    2164         130 :         SSL_CTX *ssl_ctx = data->ssl;
    2165             : 
    2166         130 :         if (ca_cert) {
    2167         130 :                 if (SSL_CTX_load_verify_locations(ssl_ctx, ca_cert, NULL) != 1)
    2168             :                 {
    2169           0 :                         tls_show_errors(MSG_WARNING, __func__,
    2170             :                                         "Failed to load root certificates");
    2171           0 :                         return -1;
    2172             :                 }
    2173             : 
    2174         130 :                 wpa_printf(MSG_DEBUG, "TLS: Trusted root "
    2175             :                            "certificate(s) loaded");
    2176             : 
    2177             : #ifndef OPENSSL_NO_STDIO
    2178             :                 /* Add the same CAs to the client certificate requests */
    2179         130 :                 SSL_CTX_set_client_CA_list(ssl_ctx,
    2180             :                                            SSL_load_client_CA_file(ca_cert));
    2181             : #endif /* OPENSSL_NO_STDIO */
    2182             :         }
    2183             : 
    2184         130 :         return 0;
    2185             : }
    2186             : 
    2187             : 
    2188         127 : int tls_global_set_verify(void *ssl_ctx, int check_crl)
    2189             : {
    2190             :         int flags;
    2191             : 
    2192         127 :         if (check_crl) {
    2193           3 :                 struct tls_data *data = ssl_ctx;
    2194           3 :                 X509_STORE *cs = SSL_CTX_get_cert_store(data->ssl);
    2195           3 :                 if (cs == NULL) {
    2196           0 :                         tls_show_errors(MSG_INFO, __func__, "Failed to get "
    2197             :                                         "certificate store when enabling "
    2198             :                                         "check_crl");
    2199           0 :                         return -1;
    2200             :                 }
    2201           3 :                 flags = X509_V_FLAG_CRL_CHECK;
    2202           3 :                 if (check_crl == 2)
    2203           1 :                         flags |= X509_V_FLAG_CRL_CHECK_ALL;
    2204           3 :                 X509_STORE_set_flags(cs, flags);
    2205             :         }
    2206         127 :         return 0;
    2207             : }
    2208             : 
    2209             : 
    2210         602 : static int tls_connection_set_subject_match(struct tls_connection *conn,
    2211             :                                             const char *subject_match,
    2212             :                                             const char *altsubject_match,
    2213             :                                             const char *suffix_match,
    2214             :                                             const char *domain_match)
    2215             : {
    2216         602 :         os_free(conn->subject_match);
    2217         602 :         conn->subject_match = NULL;
    2218         602 :         if (subject_match) {
    2219           6 :                 conn->subject_match = os_strdup(subject_match);
    2220           6 :                 if (conn->subject_match == NULL)
    2221           1 :                         return -1;
    2222             :         }
    2223             : 
    2224         601 :         os_free(conn->altsubject_match);
    2225         601 :         conn->altsubject_match = NULL;
    2226         601 :         if (altsubject_match) {
    2227          11 :                 conn->altsubject_match = os_strdup(altsubject_match);
    2228          11 :                 if (conn->altsubject_match == NULL)
    2229           1 :                         return -1;
    2230             :         }
    2231             : 
    2232         600 :         os_free(conn->suffix_match);
    2233         600 :         conn->suffix_match = NULL;
    2234         600 :         if (suffix_match) {
    2235          15 :                 conn->suffix_match = os_strdup(suffix_match);
    2236          15 :                 if (conn->suffix_match == NULL)
    2237           1 :                         return -1;
    2238             :         }
    2239             : 
    2240         599 :         os_free(conn->domain_match);
    2241         599 :         conn->domain_match = NULL;
    2242         599 :         if (domain_match) {
    2243           6 :                 conn->domain_match = os_strdup(domain_match);
    2244           6 :                 if (conn->domain_match == NULL)
    2245           1 :                         return -1;
    2246             :         }
    2247             : 
    2248         598 :         return 0;
    2249             : }
    2250             : 
    2251             : 
    2252        1522 : static void tls_set_conn_flags(SSL *ssl, unsigned int flags)
    2253             : {
    2254             : #ifdef SSL_OP_NO_TICKET
    2255        1522 :         if (flags & TLS_CONN_DISABLE_SESSION_TICKET)
    2256        1211 :                 SSL_set_options(ssl, SSL_OP_NO_TICKET);
    2257             : #ifdef SSL_clear_options
    2258             :         else
    2259         311 :                 SSL_clear_options(ssl, SSL_OP_NO_TICKET);
    2260             : #endif /* SSL_clear_options */
    2261             : #endif /* SSL_OP_NO_TICKET */
    2262             : 
    2263             : #ifdef SSL_OP_NO_TLSv1
    2264        1522 :         if (flags & TLS_CONN_DISABLE_TLSv1_0)
    2265           2 :                 SSL_set_options(ssl, SSL_OP_NO_TLSv1);
    2266             :         else
    2267        1520 :                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1);
    2268             : #endif /* SSL_OP_NO_TLSv1 */
    2269             : #ifdef SSL_OP_NO_TLSv1_1
    2270        1522 :         if (flags & TLS_CONN_DISABLE_TLSv1_1)
    2271           2 :                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_1);
    2272             :         else
    2273        1520 :                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_1);
    2274             : #endif /* SSL_OP_NO_TLSv1_1 */
    2275             : #ifdef SSL_OP_NO_TLSv1_2
    2276        1522 :         if (flags & TLS_CONN_DISABLE_TLSv1_2)
    2277           2 :                 SSL_set_options(ssl, SSL_OP_NO_TLSv1_2);
    2278             :         else
    2279        1520 :                 SSL_clear_options(ssl, SSL_OP_NO_TLSv1_2);
    2280             : #endif /* SSL_OP_NO_TLSv1_2 */
    2281        1522 : }
    2282             : 
    2283             : 
    2284         929 : int tls_connection_set_verify(void *ssl_ctx, struct tls_connection *conn,
    2285             :                               int verify_peer, unsigned int flags,
    2286             :                               const u8 *session_ctx, size_t session_ctx_len)
    2287             : {
    2288             :         static int counter = 0;
    2289         929 :         struct tls_data *data = ssl_ctx;
    2290             : 
    2291         929 :         if (conn == NULL)
    2292           0 :                 return -1;
    2293             : 
    2294         929 :         if (verify_peer) {
    2295          86 :                 conn->ca_cert_verify = 1;
    2296          86 :                 SSL_set_verify(conn->ssl, SSL_VERIFY_PEER |
    2297             :                                SSL_VERIFY_FAIL_IF_NO_PEER_CERT |
    2298             :                                SSL_VERIFY_CLIENT_ONCE, tls_verify_cb);
    2299             :         } else {
    2300         843 :                 conn->ca_cert_verify = 0;
    2301         843 :                 SSL_set_verify(conn->ssl, SSL_VERIFY_NONE, NULL);
    2302             :         }
    2303             : 
    2304         929 :         tls_set_conn_flags(conn->ssl, flags);
    2305         929 :         conn->flags = flags;
    2306             : 
    2307         929 :         SSL_set_accept_state(conn->ssl);
    2308             : 
    2309         929 :         if (data->tls_session_lifetime == 0) {
    2310             :                 /*
    2311             :                  * Set session id context to a unique value to make sure
    2312             :                  * session resumption cannot be used either through session
    2313             :                  * caching or TLS ticket extension.
    2314             :                  */
    2315         895 :                 counter++;
    2316         895 :                 SSL_set_session_id_context(conn->ssl,
    2317             :                                            (const unsigned char *) &counter,
    2318             :                                            sizeof(counter));
    2319          34 :         } else if (session_ctx) {
    2320          34 :                 SSL_set_session_id_context(conn->ssl, session_ctx,
    2321             :                                            session_ctx_len);
    2322             :         }
    2323             : 
    2324         929 :         return 0;
    2325             : }
    2326             : 
    2327             : 
    2328         595 : static int tls_connection_client_cert(struct tls_connection *conn,
    2329             :                                       const char *client_cert,
    2330             :                                       const u8 *client_cert_blob,
    2331             :                                       size_t client_cert_blob_len)
    2332             : {
    2333         595 :         if (client_cert == NULL && client_cert_blob == NULL)
    2334         544 :                 return 0;
    2335             : 
    2336             : #ifdef PKCS12_FUNCS
    2337             : #if OPENSSL_VERSION_NUMBER < 0x10002000L
    2338             :         /*
    2339             :          * Clear previously set extra chain certificates, if any, from PKCS#12
    2340             :          * processing in tls_parse_pkcs12() to allow OpenSSL to build a new
    2341             :          * chain properly.
    2342             :          */
    2343             :         SSL_CTX_clear_extra_chain_certs(conn->ssl_ctx);
    2344             : #endif /* OPENSSL_VERSION_NUMBER < 0x10002000L */
    2345             : #endif /* PKCS12_FUNCS */
    2346             : 
    2347          52 :         if (client_cert_blob &&
    2348           1 :             SSL_use_certificate_ASN1(conn->ssl, (u8 *) client_cert_blob,
    2349             :                                      client_cert_blob_len) == 1) {
    2350           1 :                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_ASN1 --> "
    2351             :                            "OK");
    2352           1 :                 return 0;
    2353          50 :         } else if (client_cert_blob) {
    2354           0 :                 tls_show_errors(MSG_DEBUG, __func__,
    2355             :                                 "SSL_use_certificate_ASN1 failed");
    2356             :         }
    2357             : 
    2358          50 :         if (client_cert == NULL)
    2359           0 :                 return -1;
    2360             : 
    2361             : #ifdef ANDROID
    2362             :         if (os_strncmp("keystore://", client_cert, 11) == 0) {
    2363             :                 BIO *bio = BIO_from_keystore(&client_cert[11]);
    2364             :                 X509 *x509 = NULL;
    2365             :                 int ret = -1;
    2366             :                 if (bio) {
    2367             :                         x509 = PEM_read_bio_X509(bio, NULL, NULL, NULL);
    2368             :                         BIO_free(bio);
    2369             :                 }
    2370             :                 if (x509) {
    2371             :                         if (SSL_use_certificate(conn->ssl, x509) == 1)
    2372             :                                 ret = 0;
    2373             :                         X509_free(x509);
    2374             :                 }
    2375             :                 return ret;
    2376             :         }
    2377             : #endif /* ANDROID */
    2378             : 
    2379             : #ifndef OPENSSL_NO_STDIO
    2380          50 :         if (SSL_use_certificate_file(conn->ssl, client_cert,
    2381             :                                      SSL_FILETYPE_ASN1) == 1) {
    2382           0 :                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (DER)"
    2383             :                            " --> OK");
    2384           0 :                 return 0;
    2385             :         }
    2386             : 
    2387          50 :         if (SSL_use_certificate_file(conn->ssl, client_cert,
    2388             :                                      SSL_FILETYPE_PEM) == 1) {
    2389          50 :                 ERR_clear_error();
    2390          50 :                 wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_certificate_file (PEM)"
    2391             :                            " --> OK");
    2392          50 :                 return 0;
    2393             :         }
    2394             : 
    2395           0 :         tls_show_errors(MSG_DEBUG, __func__,
    2396             :                         "SSL_use_certificate_file failed");
    2397             : #else /* OPENSSL_NO_STDIO */
    2398             :         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
    2399             : #endif /* OPENSSL_NO_STDIO */
    2400             : 
    2401           0 :         return -1;
    2402             : }
    2403             : 
    2404             : 
    2405         130 : static int tls_global_client_cert(struct tls_data *data,
    2406             :                                   const char *client_cert)
    2407             : {
    2408             : #ifndef OPENSSL_NO_STDIO
    2409         130 :         SSL_CTX *ssl_ctx = data->ssl;
    2410             : 
    2411         130 :         if (client_cert == NULL)
    2412           2 :                 return 0;
    2413             : 
    2414         128 :         if (SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
    2415         128 :                                          SSL_FILETYPE_ASN1) != 1 &&
    2416         128 :             SSL_CTX_use_certificate_chain_file(ssl_ctx, client_cert) != 1 &&
    2417           0 :             SSL_CTX_use_certificate_file(ssl_ctx, client_cert,
    2418             :                                          SSL_FILETYPE_PEM) != 1) {
    2419           0 :                 tls_show_errors(MSG_INFO, __func__,
    2420             :                                 "Failed to load client certificate");
    2421           0 :                 return -1;
    2422             :         }
    2423         128 :         return 0;
    2424             : #else /* OPENSSL_NO_STDIO */
    2425             :         if (client_cert == NULL)
    2426             :                 return 0;
    2427             :         wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO", __func__);
    2428             :         return -1;
    2429             : #endif /* OPENSSL_NO_STDIO */
    2430             : }
    2431             : 
    2432             : 
    2433           2 : static int tls_passwd_cb(char *buf, int size, int rwflag, void *password)
    2434             : {
    2435           2 :         if (password == NULL) {
    2436           0 :                 return 0;
    2437             :         }
    2438           2 :         os_strlcpy(buf, (char *) password, size);
    2439           2 :         return os_strlen(buf);
    2440             : }
    2441             : 
    2442             : 
    2443             : #ifdef PKCS12_FUNCS
    2444          26 : static int tls_parse_pkcs12(struct tls_data *data, SSL *ssl, PKCS12 *p12,
    2445             :                             const char *passwd)
    2446             : {
    2447             :         EVP_PKEY *pkey;
    2448             :         X509 *cert;
    2449             :         STACK_OF(X509) *certs;
    2450          26 :         int res = 0;
    2451             :         char buf[256];
    2452             : 
    2453          26 :         pkey = NULL;
    2454          26 :         cert = NULL;
    2455          26 :         certs = NULL;
    2456          26 :         if (!passwd)
    2457           2 :                 passwd = "";
    2458          26 :         if (!PKCS12_parse(p12, passwd, &pkey, &cert, &certs)) {
    2459           1 :                 tls_show_errors(MSG_DEBUG, __func__,
    2460             :                                 "Failed to parse PKCS12 file");
    2461           1 :                 PKCS12_free(p12);
    2462           1 :                 return -1;
    2463             :         }
    2464          25 :         wpa_printf(MSG_DEBUG, "TLS: Successfully parsed PKCS12 data");
    2465             : 
    2466          25 :         if (cert) {
    2467          25 :                 X509_NAME_oneline(X509_get_subject_name(cert), buf,
    2468             :                                   sizeof(buf));
    2469          25 :                 wpa_printf(MSG_DEBUG, "TLS: Got certificate from PKCS12: "
    2470             :                            "subject='%s'", buf);
    2471          25 :                 if (ssl) {
    2472          23 :                         if (SSL_use_certificate(ssl, cert) != 1)
    2473           0 :                                 res = -1;
    2474             :                 } else {
    2475           2 :                         if (SSL_CTX_use_certificate(data->ssl, cert) != 1)
    2476           0 :                                 res = -1;
    2477             :                 }
    2478          25 :                 X509_free(cert);
    2479             :         }
    2480             : 
    2481          25 :         if (pkey) {
    2482          25 :                 wpa_printf(MSG_DEBUG, "TLS: Got private key from PKCS12");
    2483          25 :                 if (ssl) {
    2484          23 :                         if (SSL_use_PrivateKey(ssl, pkey) != 1)
    2485           0 :                                 res = -1;
    2486             :                 } else {
    2487           2 :                         if (SSL_CTX_use_PrivateKey(data->ssl, pkey) != 1)
    2488           0 :                                 res = -1;
    2489             :                 }
    2490          25 :                 EVP_PKEY_free(pkey);
    2491             :         }
    2492             : 
    2493          25 :         if (certs) {
    2494             : #if OPENSSL_VERSION_NUMBER >= 0x10002000L && !defined(LIBRESSL_VERSION_NUMBER)
    2495           5 :                 if (ssl)
    2496           4 :                         SSL_clear_chain_certs(ssl);
    2497             :                 else
    2498           1 :                         SSL_CTX_clear_chain_certs(data->ssl);
    2499          15 :                 while ((cert = sk_X509_pop(certs)) != NULL) {
    2500           5 :                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
    2501             :                                           sizeof(buf));
    2502           5 :                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
    2503             :                                    " from PKCS12: subject='%s'", buf);
    2504           5 :                         if ((ssl && SSL_add1_chain_cert(ssl, cert) != 1) ||
    2505           1 :                             (!ssl && SSL_CTX_add1_chain_cert(data->ssl,
    2506             :                                                              cert) != 1)) {
    2507           0 :                                 tls_show_errors(MSG_DEBUG, __func__,
    2508             :                                                 "Failed to add additional certificate");
    2509           0 :                                 res = -1;
    2510           0 :                                 X509_free(cert);
    2511           0 :                                 break;
    2512             :                         }
    2513           5 :                         X509_free(cert);
    2514             :                 }
    2515             :                 if (!res) {
    2516             :                         /* Try to continue anyway */
    2517             :                 }
    2518           5 :                 sk_X509_pop_free(certs, X509_free);
    2519             : #ifndef OPENSSL_IS_BORINGSSL
    2520           5 :                 if (ssl)
    2521           4 :                         res = SSL_build_cert_chain(
    2522             :                                 ssl,
    2523             :                                 SSL_BUILD_CHAIN_FLAG_CHECK |
    2524             :                                 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
    2525             :                 else
    2526           1 :                         res = SSL_CTX_build_cert_chain(
    2527             :                                 data->ssl,
    2528             :                                 SSL_BUILD_CHAIN_FLAG_CHECK |
    2529             :                                 SSL_BUILD_CHAIN_FLAG_IGNORE_ERROR);
    2530           5 :                 if (!res) {
    2531           0 :                         tls_show_errors(MSG_DEBUG, __func__,
    2532             :                                         "Failed to build certificate chain");
    2533           5 :                 } else if (res == 2) {
    2534           3 :                         wpa_printf(MSG_DEBUG,
    2535             :                                    "TLS: Ignore certificate chain verification error when building chain with PKCS#12 extra certificates");
    2536             :                 }
    2537             : #endif /* OPENSSL_IS_BORINGSSL */
    2538             :                 /*
    2539             :                  * Try to continue regardless of result since it is possible for
    2540             :                  * the extra certificates not to be required.
    2541             :                  */
    2542           5 :                 res = 0;
    2543             : #else /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
    2544             :                 SSL_CTX_clear_extra_chain_certs(data->ssl);
    2545             :                 while ((cert = sk_X509_pop(certs)) != NULL) {
    2546             :                         X509_NAME_oneline(X509_get_subject_name(cert), buf,
    2547             :                                           sizeof(buf));
    2548             :                         wpa_printf(MSG_DEBUG, "TLS: additional certificate"
    2549             :                                    " from PKCS12: subject='%s'", buf);
    2550             :                         /*
    2551             :                          * There is no SSL equivalent for the chain cert - so
    2552             :                          * always add it to the context...
    2553             :                          */
    2554             :                         if (SSL_CTX_add_extra_chain_cert(data->ssl, cert) != 1)
    2555             :                         {
    2556             :                                 X509_free(cert);
    2557             :                                 res = -1;
    2558             :                                 break;
    2559             :                         }
    2560             :                 }
    2561             :                 sk_X509_pop_free(certs, X509_free);
    2562             : #endif /* OPENSSL_VERSION_NUMBER >= 0x10002000L */
    2563             :         }
    2564             : 
    2565          25 :         PKCS12_free(p12);
    2566             : 
    2567          25 :         if (res < 0)
    2568           0 :                 tls_get_errors(data);
    2569             : 
    2570          25 :         return res;
    2571             : }
    2572             : #endif  /* PKCS12_FUNCS */
    2573             : 
    2574             : 
    2575          25 : static int tls_read_pkcs12(struct tls_data *data, SSL *ssl,
    2576             :                            const char *private_key, const char *passwd)
    2577             : {
    2578             : #ifdef PKCS12_FUNCS
    2579             :         FILE *f;
    2580             :         PKCS12 *p12;
    2581             : 
    2582          25 :         f = fopen(private_key, "rb");
    2583          25 :         if (f == NULL)
    2584           0 :                 return -1;
    2585             : 
    2586          25 :         p12 = d2i_PKCS12_fp(f, NULL);
    2587          25 :         fclose(f);
    2588             : 
    2589          25 :         if (p12 == NULL) {
    2590           0 :                 tls_show_errors(MSG_INFO, __func__,
    2591             :                                 "Failed to use PKCS#12 file");
    2592           0 :                 return -1;
    2593             :         }
    2594             : 
    2595          25 :         return tls_parse_pkcs12(data, ssl, p12, passwd);
    2596             : 
    2597             : #else /* PKCS12_FUNCS */
    2598             :         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot read "
    2599             :                    "p12/pfx files");
    2600             :         return -1;
    2601             : #endif  /* PKCS12_FUNCS */
    2602             : }
    2603             : 
    2604             : 
    2605           1 : static int tls_read_pkcs12_blob(struct tls_data *data, SSL *ssl,
    2606             :                                 const u8 *blob, size_t len, const char *passwd)
    2607             : {
    2608             : #ifdef PKCS12_FUNCS
    2609             :         PKCS12 *p12;
    2610             : 
    2611           1 :         p12 = d2i_PKCS12(NULL, (const unsigned char **) &blob, len);
    2612           1 :         if (p12 == NULL) {
    2613           0 :                 tls_show_errors(MSG_INFO, __func__,
    2614             :                                 "Failed to use PKCS#12 blob");
    2615           0 :                 return -1;
    2616             :         }
    2617             : 
    2618           1 :         return tls_parse_pkcs12(data, ssl, p12, passwd);
    2619             : 
    2620             : #else /* PKCS12_FUNCS */
    2621             :         wpa_printf(MSG_INFO, "TLS: PKCS12 support disabled - cannot parse "
    2622             :                    "p12/pfx blobs");
    2623             :         return -1;
    2624             : #endif  /* PKCS12_FUNCS */
    2625             : }
    2626             : 
    2627             : 
    2628             : #ifndef OPENSSL_NO_ENGINE
    2629             : static int tls_engine_get_cert(struct tls_connection *conn,
    2630             :                                const char *cert_id,
    2631             :                                X509 **cert)
    2632             : {
    2633             :         /* this runs after the private key is loaded so no PIN is required */
    2634             :         struct {
    2635             :                 const char *cert_id;
    2636             :                 X509 *cert;
    2637             :         } params;
    2638             :         params.cert_id = cert_id;
    2639             :         params.cert = NULL;
    2640             : 
    2641             :         if (!ENGINE_ctrl_cmd(conn->engine, "LOAD_CERT_CTRL",
    2642             :                              0, &params, NULL, 1)) {
    2643             :                 unsigned long err = ERR_get_error();
    2644             : 
    2645             :                 wpa_printf(MSG_ERROR, "ENGINE: cannot load client cert with id"
    2646             :                            " '%s' [%s]", cert_id,
    2647             :                            ERR_error_string(err, NULL));
    2648             :                 if (tls_is_pin_error(err))
    2649             :                         return TLS_SET_PARAMS_ENGINE_PRV_BAD_PIN;
    2650             :                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
    2651             :         }
    2652             :         if (!params.cert) {
    2653             :                 wpa_printf(MSG_ERROR, "ENGINE: did not properly cert with id"
    2654             :                            " '%s'", cert_id);
    2655             :                 return TLS_SET_PARAMS_ENGINE_PRV_INIT_FAILED;
    2656             :         }
    2657             :         *cert = params.cert;
    2658             :         return 0;
    2659             : }
    2660             : #endif /* OPENSSL_NO_ENGINE */
    2661             : 
    2662             : 
    2663           0 : static int tls_connection_engine_client_cert(struct tls_connection *conn,
    2664             :                                              const char *cert_id)
    2665             : {
    2666             : #ifndef OPENSSL_NO_ENGINE
    2667             :         X509 *cert;
    2668             : 
    2669             :         if (tls_engine_get_cert(conn, cert_id, &cert))
    2670             :                 return -1;
    2671             : 
    2672             :         if (!SSL_use_certificate(conn->ssl, cert)) {
    2673             :                 tls_show_errors(MSG_ERROR, __func__,
    2674             :                                 "SSL_use_certificate failed");
    2675             :                 X509_free(cert);
    2676             :                 return -1;
    2677             :         }
    2678             :         X509_free(cert);
    2679             :         wpa_printf(MSG_DEBUG, "ENGINE: SSL_use_certificate --> "
    2680             :                    "OK");
    2681             :         return 0;
    2682             : 
    2683             : #else /* OPENSSL_NO_ENGINE */
    2684           0 :         return -1;
    2685             : #endif /* OPENSSL_NO_ENGINE */
    2686             : }
    2687             : 
    2688             : 
    2689           0 : static int tls_connection_engine_ca_cert(struct tls_data *data,
    2690             :                                          struct tls_connection *conn,
    2691             :                                          const char *ca_cert_id)
    2692             : {
    2693             : #ifndef OPENSSL_NO_ENGINE
    2694             :         X509 *cert;
    2695             :         SSL_CTX *ssl_ctx = data->ssl;
    2696             :         X509_STORE *store;
    2697             : 
    2698             :         if (tls_engine_get_cert(conn, ca_cert_id, &cert))
    2699             :                 return -1;
    2700             : 
    2701             :         /* start off the same as tls_connection_ca_cert */
    2702             :         store = X509_STORE_new();
    2703             :         if (store == NULL) {
    2704             :                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - failed to allocate new "
    2705             :                            "certificate store", __func__);
    2706             :                 X509_free(cert);
    2707             :                 return -1;
    2708             :         }
    2709             :         SSL_CTX_set_cert_store(ssl_ctx, store);
    2710             :         if (!X509_STORE_add_cert(store, cert)) {
    2711             :                 unsigned long err = ERR_peek_error();
    2712             :                 tls_show_errors(MSG_WARNING, __func__,
    2713             :                                 "Failed to add CA certificate from engine "
    2714             :                                 "to certificate store");
    2715             :                 if (ERR_GET_LIB(err) == ERR_LIB_X509 &&
    2716             :                     ERR_GET_REASON(err) == X509_R_CERT_ALREADY_IN_HASH_TABLE) {
    2717             :                         wpa_printf(MSG_DEBUG, "OpenSSL: %s - ignoring cert"
    2718             :                                    " already in hash table error",
    2719             :                                    __func__);
    2720             :                 } else {
    2721             :                         X509_free(cert);
    2722             :                         return -1;
    2723             :                 }
    2724             :         }
    2725             :         X509_free(cert);
    2726             :         wpa_printf(MSG_DEBUG, "OpenSSL: %s - added CA certificate from engine "
    2727             :                    "to certificate store", __func__);
    2728             :         SSL_set_verify(conn->ssl, SSL_VERIFY_PEER, tls_verify_cb);
    2729             :         conn->ca_cert_verify = 1;
    2730             : 
    2731             :         return 0;
    2732             : 
    2733             : #else /* OPENSSL_NO_ENGINE */
    2734           0 :         return -1;
    2735             : #endif /* OPENSSL_NO_ENGINE */
    2736             : }
    2737             : 
    2738             : 
    2739           0 : static int tls_connection_engine_private_key(struct tls_connection *conn)
    2740             : {
    2741             : #if defined(ANDROID) || !defined(OPENSSL_NO_ENGINE)
    2742             :         if (SSL_use_PrivateKey(conn->ssl, conn->private_key) != 1) {
    2743             :                 tls_show_errors(MSG_ERROR, __func__,
    2744             :                                 "ENGINE: cannot use private key for TLS");
    2745             :                 return -1;
    2746             :         }
    2747             :         if (!SSL_check_private_key(conn->ssl)) {
    2748             :                 tls_show_errors(MSG_INFO, __func__,
    2749             :                                 "Private key failed verification");
    2750             :                 return -1;
    2751             :         }
    2752             :         return 0;
    2753             : #else /* OPENSSL_NO_ENGINE */
    2754           0 :         wpa_printf(MSG_ERROR, "SSL: Configuration uses engine, but "
    2755             :                    "engine support was not compiled in");
    2756           0 :         return -1;
    2757             : #endif /* OPENSSL_NO_ENGINE */
    2758             : }
    2759             : 
    2760             : 
    2761         595 : static int tls_connection_private_key(struct tls_data *data,
    2762             :                                       struct tls_connection *conn,
    2763             :                                       const char *private_key,
    2764             :                                       const char *private_key_passwd,
    2765             :                                       const u8 *private_key_blob,
    2766             :                                       size_t private_key_blob_len)
    2767             : {
    2768         595 :         SSL_CTX *ssl_ctx = data->ssl;
    2769             :         char *passwd;
    2770             :         int ok;
    2771             : 
    2772         595 :         if (private_key == NULL && private_key_blob == NULL)
    2773         520 :                 return 0;
    2774             : 
    2775          75 :         if (private_key_passwd) {
    2776          25 :                 passwd = os_strdup(private_key_passwd);
    2777          25 :                 if (passwd == NULL)
    2778           0 :                         return -1;
    2779             :         } else
    2780          50 :                 passwd = NULL;
    2781             : 
    2782          75 :         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
    2783          75 :         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
    2784             : 
    2785          75 :         ok = 0;
    2786          75 :         while (private_key_blob) {
    2787           2 :                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_RSA, conn->ssl,
    2788             :                                             (u8 *) private_key_blob,
    2789             :                                             private_key_blob_len) == 1) {
    2790           1 :                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
    2791             :                                    "ASN1(EVP_PKEY_RSA) --> OK");
    2792           1 :                         ok = 1;
    2793           1 :                         break;
    2794             :                 }
    2795             : 
    2796           1 :                 if (SSL_use_PrivateKey_ASN1(EVP_PKEY_DSA, conn->ssl,
    2797             :                                             (u8 *) private_key_blob,
    2798             :                                             private_key_blob_len) == 1) {
    2799           0 :                         wpa_printf(MSG_DEBUG, "OpenSSL: SSL_use_PrivateKey_"
    2800             :                                    "ASN1(EVP_PKEY_DSA) --> OK");
    2801           0 :                         ok = 1;
    2802           0 :                         break;
    2803             :                 }
    2804             : 
    2805           1 :                 if (SSL_use_RSAPrivateKey_ASN1(conn->ssl,
    2806             :                                                (u8 *) private_key_blob,
    2807             :                                                private_key_blob_len) == 1) {
    2808           0 :                         wpa_printf(MSG_DEBUG, "OpenSSL: "
    2809             :                                    "SSL_use_RSAPrivateKey_ASN1 --> OK");
    2810           0 :                         ok = 1;
    2811           0 :                         break;
    2812             :                 }
    2813             : 
    2814           1 :                 if (tls_read_pkcs12_blob(data, conn->ssl, private_key_blob,
    2815             :                                          private_key_blob_len, passwd) == 0) {
    2816           1 :                         wpa_printf(MSG_DEBUG, "OpenSSL: PKCS#12 as blob --> "
    2817             :                                    "OK");
    2818           1 :                         ok = 1;
    2819           1 :                         break;
    2820             :                 }
    2821             : 
    2822           0 :                 break;
    2823             :         }
    2824             : 
    2825         148 :         while (!ok && private_key) {
    2826             : #ifndef OPENSSL_NO_STDIO
    2827          73 :                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
    2828             :                                             SSL_FILETYPE_ASN1) == 1) {
    2829           0 :                         wpa_printf(MSG_DEBUG, "OpenSSL: "
    2830             :                                    "SSL_use_PrivateKey_File (DER) --> OK");
    2831           0 :                         ok = 1;
    2832           0 :                         break;
    2833             :                 }
    2834             : 
    2835          73 :                 if (SSL_use_PrivateKey_file(conn->ssl, private_key,
    2836             :                                             SSL_FILETYPE_PEM) == 1) {
    2837          50 :                         wpa_printf(MSG_DEBUG, "OpenSSL: "
    2838             :                                    "SSL_use_PrivateKey_File (PEM) --> OK");
    2839          50 :                         ok = 1;
    2840          50 :                         break;
    2841             :                 }
    2842             : #else /* OPENSSL_NO_STDIO */
    2843             :                 wpa_printf(MSG_DEBUG, "OpenSSL: %s - OPENSSL_NO_STDIO",
    2844             :                            __func__);
    2845             : #endif /* OPENSSL_NO_STDIO */
    2846             : 
    2847          23 :                 if (tls_read_pkcs12(data, conn->ssl, private_key, passwd)
    2848             :                     == 0) {
    2849          22 :                         wpa_printf(MSG_DEBUG, "OpenSSL: Reading PKCS#12 file "
    2850             :                                    "--> OK");
    2851          22 :                         ok = 1;
    2852          22 :                         break;
    2853             :                 }
    2854             : 
    2855           1 :                 if (tls_cryptoapi_cert(conn->ssl, private_key) == 0) {
    2856           0 :                         wpa_printf(MSG_DEBUG, "OpenSSL: Using CryptoAPI to "
    2857             :                                    "access certificate store --> OK");
    2858           0 :                         ok = 1;
    2859           0 :                         break;
    2860             :                 }
    2861             : 
    2862           1 :                 break;
    2863             :         }
    2864             : 
    2865          75 :         if (!ok) {
    2866           1 :                 tls_show_errors(MSG_INFO, __func__,
    2867             :                                 "Failed to load private key");
    2868           1 :                 os_free(passwd);
    2869           1 :                 return -1;
    2870             :         }
    2871          74 :         ERR_clear_error();
    2872          74 :         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
    2873          74 :         os_free(passwd);
    2874             : 
    2875          74 :         if (!SSL_check_private_key(conn->ssl)) {
    2876           0 :                 tls_show_errors(MSG_INFO, __func__, "Private key failed "
    2877             :                                 "verification");
    2878           0 :                 return -1;
    2879             :         }
    2880             : 
    2881          74 :         wpa_printf(MSG_DEBUG, "SSL: Private key loaded successfully");
    2882          74 :         return 0;
    2883             : }
    2884             : 
    2885             : 
    2886         130 : static int tls_global_private_key(struct tls_data *data,
    2887             :                                   const char *private_key,
    2888             :                                   const char *private_key_passwd)
    2889             : {
    2890         130 :         SSL_CTX *ssl_ctx = data->ssl;
    2891             :         char *passwd;
    2892             : 
    2893         130 :         if (private_key == NULL)
    2894           0 :                 return 0;
    2895             : 
    2896         130 :         if (private_key_passwd) {
    2897           1 :                 passwd = os_strdup(private_key_passwd);
    2898           1 :                 if (passwd == NULL)
    2899           0 :                         return -1;
    2900             :         } else
    2901         129 :                 passwd = NULL;
    2902             : 
    2903         130 :         SSL_CTX_set_default_passwd_cb(ssl_ctx, tls_passwd_cb);
    2904         130 :         SSL_CTX_set_default_passwd_cb_userdata(ssl_ctx, passwd);
    2905         130 :         if (
    2906             : #ifndef OPENSSL_NO_STDIO
    2907         130 :             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
    2908         130 :                                         SSL_FILETYPE_ASN1) != 1 &&
    2909         130 :             SSL_CTX_use_PrivateKey_file(ssl_ctx, private_key,
    2910           2 :                                         SSL_FILETYPE_PEM) != 1 &&
    2911             : #endif /* OPENSSL_NO_STDIO */
    2912           2 :             tls_read_pkcs12(data, NULL, private_key, passwd)) {
    2913           0 :                 tls_show_errors(MSG_INFO, __func__,
    2914             :                                 "Failed to load private key");
    2915           0 :                 os_free(passwd);
    2916           0 :                 ERR_clear_error();
    2917           0 :                 return -1;
    2918             :         }
    2919         130 :         os_free(passwd);
    2920         130 :         ERR_clear_error();
    2921         130 :         SSL_CTX_set_default_passwd_cb(ssl_ctx, NULL);
    2922             : 
    2923         130 :         if (!SSL_CTX_check_private_key(ssl_ctx)) {
    2924           0 :                 tls_show_errors(MSG_INFO, __func__,
    2925             :                                 "Private key failed verification");
    2926           0 :                 return -1;
    2927             :         }
    2928             : 
    2929         130 :         return 0;
    2930             : }
    2931             : 
    2932             : 
    2933         594 : static int tls_connection_dh(struct tls_connection *conn, const char *dh_file)
    2934             : {
    2935             : #ifdef OPENSSL_NO_DH
    2936             :         if (dh_file == NULL)
    2937             :                 return 0;
    2938             :         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
    2939             :                    "dh_file specified");
    2940             :         return -1;
    2941             : #else /* OPENSSL_NO_DH */
    2942             :         DH *dh;
    2943             :         BIO *bio;
    2944             : 
    2945             :         /* TODO: add support for dh_blob */
    2946         594 :         if (dh_file == NULL)
    2947         592 :                 return 0;
    2948           2 :         if (conn == NULL)
    2949           0 :                 return -1;
    2950             : 
    2951           2 :         bio = BIO_new_file(dh_file, "r");
    2952           2 :         if (bio == NULL) {
    2953           0 :                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
    2954             :                            dh_file, ERR_error_string(ERR_get_error(), NULL));
    2955           0 :                 return -1;
    2956             :         }
    2957           2 :         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
    2958           2 :         BIO_free(bio);
    2959             : #ifndef OPENSSL_NO_DSA
    2960           2 :         while (dh == NULL) {
    2961             :                 DSA *dsa;
    2962           1 :                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
    2963             :                            " trying to parse as DSA params", dh_file,
    2964             :                            ERR_error_string(ERR_get_error(), NULL));
    2965           1 :                 bio = BIO_new_file(dh_file, "r");
    2966           1 :                 if (bio == NULL)
    2967           0 :                         break;
    2968           1 :                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
    2969           1 :                 BIO_free(bio);
    2970           1 :                 if (!dsa) {
    2971           0 :                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
    2972             :                                    "'%s': %s", dh_file,
    2973             :                                    ERR_error_string(ERR_get_error(), NULL));
    2974           0 :                         break;
    2975             :                 }
    2976             : 
    2977           1 :                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
    2978           1 :                 dh = DSA_dup_DH(dsa);
    2979           1 :                 DSA_free(dsa);
    2980           1 :                 if (dh == NULL) {
    2981           0 :                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
    2982             :                                    "params into DH params");
    2983           0 :                         break;
    2984             :                 }
    2985           1 :                 break;
    2986             :         }
    2987             : #endif /* !OPENSSL_NO_DSA */
    2988           2 :         if (dh == NULL) {
    2989           0 :                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
    2990             :                            "'%s'", dh_file);
    2991           0 :                 return -1;
    2992             :         }
    2993             : 
    2994           2 :         if (SSL_set_tmp_dh(conn->ssl, dh) != 1) {
    2995           0 :                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
    2996             :                            "%s", dh_file,
    2997             :                            ERR_error_string(ERR_get_error(), NULL));
    2998           0 :                 DH_free(dh);
    2999           0 :                 return -1;
    3000             :         }
    3001           2 :         DH_free(dh);
    3002           2 :         return 0;
    3003             : #endif /* OPENSSL_NO_DH */
    3004             : }
    3005             : 
    3006             : 
    3007         130 : static int tls_global_dh(struct tls_data *data, const char *dh_file)
    3008             : {
    3009             : #ifdef OPENSSL_NO_DH
    3010             :         if (dh_file == NULL)
    3011             :                 return 0;
    3012             :         wpa_printf(MSG_ERROR, "TLS: openssl does not include DH support, but "
    3013             :                    "dh_file specified");
    3014             :         return -1;
    3015             : #else /* OPENSSL_NO_DH */
    3016         130 :         SSL_CTX *ssl_ctx = data->ssl;
    3017             :         DH *dh;
    3018             :         BIO *bio;
    3019             : 
    3020             :         /* TODO: add support for dh_blob */
    3021         130 :         if (dh_file == NULL)
    3022          24 :                 return 0;
    3023         106 :         if (ssl_ctx == NULL)
    3024           0 :                 return -1;
    3025             : 
    3026         106 :         bio = BIO_new_file(dh_file, "r");
    3027         106 :         if (bio == NULL) {
    3028           1 :                 wpa_printf(MSG_INFO, "TLS: Failed to open DH file '%s': %s",
    3029             :                            dh_file, ERR_error_string(ERR_get_error(), NULL));
    3030           1 :                 return -1;
    3031             :         }
    3032         105 :         dh = PEM_read_bio_DHparams(bio, NULL, NULL, NULL);
    3033         105 :         BIO_free(bio);
    3034             : #ifndef OPENSSL_NO_DSA
    3035         105 :         while (dh == NULL) {
    3036             :                 DSA *dsa;
    3037           2 :                 wpa_printf(MSG_DEBUG, "TLS: Failed to parse DH file '%s': %s -"
    3038             :                            " trying to parse as DSA params", dh_file,
    3039             :                            ERR_error_string(ERR_get_error(), NULL));
    3040           2 :                 bio = BIO_new_file(dh_file, "r");
    3041           2 :                 if (bio == NULL)
    3042           0 :                         break;
    3043           2 :                 dsa = PEM_read_bio_DSAparams(bio, NULL, NULL, NULL);
    3044           2 :                 BIO_free(bio);
    3045           2 :                 if (!dsa) {
    3046           1 :                         wpa_printf(MSG_DEBUG, "TLS: Failed to parse DSA file "
    3047             :                                    "'%s': %s", dh_file,
    3048             :                                    ERR_error_string(ERR_get_error(), NULL));
    3049           1 :                         break;
    3050             :                 }
    3051             : 
    3052           1 :                 wpa_printf(MSG_DEBUG, "TLS: DH file in DSA param format");
    3053           1 :                 dh = DSA_dup_DH(dsa);
    3054           1 :                 DSA_free(dsa);
    3055           1 :                 if (dh == NULL) {
    3056           0 :                         wpa_printf(MSG_INFO, "TLS: Failed to convert DSA "
    3057             :                                    "params into DH params");
    3058           0 :                         break;
    3059             :                 }
    3060           1 :                 break;
    3061             :         }
    3062             : #endif /* !OPENSSL_NO_DSA */
    3063         105 :         if (dh == NULL) {
    3064           1 :                 wpa_printf(MSG_INFO, "TLS: Failed to read/parse DH/DSA file "
    3065             :                            "'%s'", dh_file);
    3066           1 :                 return -1;
    3067             :         }
    3068             : 
    3069         104 :         if (SSL_CTX_set_tmp_dh(ssl_ctx, dh) != 1) {
    3070           0 :                 wpa_printf(MSG_INFO, "TLS: Failed to set DH params from '%s': "
    3071             :                            "%s", dh_file,
    3072             :                            ERR_error_string(ERR_get_error(), NULL));
    3073           0 :                 DH_free(dh);
    3074           0 :                 return -1;
    3075             :         }
    3076         104 :         DH_free(dh);
    3077         104 :         return 0;
    3078             : #endif /* OPENSSL_NO_DH */
    3079             : }
    3080             : 
    3081             : 
    3082         828 : int tls_connection_get_random(void *ssl_ctx, struct tls_connection *conn,
    3083             :                               struct tls_random *keys)
    3084             : {
    3085             :         SSL *ssl;
    3086             : 
    3087         828 :         if (conn == NULL || keys == NULL)
    3088           0 :                 return -1;
    3089         828 :         ssl = conn->ssl;
    3090         828 :         if (ssl == NULL)
    3091           0 :                 return -1;
    3092             : 
    3093         828 :         os_memset(keys, 0, sizeof(*keys));
    3094         828 :         keys->client_random = conn->client_random;
    3095         828 :         keys->client_random_len = SSL_get_client_random(
    3096         828 :                 ssl, conn->client_random, sizeof(conn->client_random));
    3097         828 :         keys->server_random = conn->server_random;
    3098         828 :         keys->server_random_len = SSL_get_server_random(
    3099         828 :                 ssl, conn->server_random, sizeof(conn->server_random));
    3100             : 
    3101         828 :         return 0;
    3102             : }
    3103             : 
    3104             : 
    3105             : #ifdef OPENSSL_NEED_EAP_FAST_PRF
    3106         231 : static int openssl_get_keyblock_size(SSL *ssl)
    3107             : {
    3108             : #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
    3109             :         const EVP_CIPHER *c;
    3110             :         const EVP_MD *h;
    3111             :         int md_size;
    3112             : 
    3113         462 :         if (ssl->enc_read_ctx == NULL || ssl->enc_read_ctx->cipher == NULL ||
    3114         231 :             ssl->read_hash == NULL)
    3115           0 :                 return -1;
    3116             : 
    3117         231 :         c = ssl->enc_read_ctx->cipher;
    3118         231 :         h = EVP_MD_CTX_md(ssl->read_hash);
    3119         231 :         if (h)
    3120         231 :                 md_size = EVP_MD_size(h);
    3121           0 :         else if (ssl->s3)
    3122           0 :                 md_size = ssl->s3->tmp.new_mac_secret_size;
    3123             :         else
    3124           0 :                 return -1;
    3125             : 
    3126         231 :         wpa_printf(MSG_DEBUG, "OpenSSL: keyblock size: key_len=%d MD_size=%d "
    3127             :                    "IV_len=%d", EVP_CIPHER_key_length(c), md_size,
    3128             :                    EVP_CIPHER_iv_length(c));
    3129         462 :         return 2 * (EVP_CIPHER_key_length(c) +
    3130         231 :                     md_size +
    3131         231 :                     EVP_CIPHER_iv_length(c));
    3132             : #else
    3133             :         const SSL_CIPHER *ssl_cipher;
    3134             :         int cipher, digest;
    3135             :         const EVP_CIPHER *c;
    3136             :         const EVP_MD *h;
    3137             : 
    3138             :         ssl_cipher = SSL_get_current_cipher(ssl);
    3139             :         if (!ssl_cipher)
    3140             :                 return -1;
    3141             :         cipher = SSL_CIPHER_get_cipher_nid(ssl_cipher);
    3142             :         digest = SSL_CIPHER_get_digest_nid(ssl_cipher);
    3143             :         wpa_printf(MSG_DEBUG, "OpenSSL: cipher nid %d digest nid %d",
    3144             :                    cipher, digest);
    3145             :         if (cipher < 0 || digest < 0)
    3146             :                 return -1;
    3147             :         c = EVP_get_cipherbynid(cipher);
    3148             :         h = EVP_get_digestbynid(digest);
    3149             :         if (!c || !h)
    3150             :                 return -1;
    3151             : 
    3152             :         wpa_printf(MSG_DEBUG,
    3153             :                    "OpenSSL: keyblock size: key_len=%d MD_size=%d IV_len=%d",
    3154             :                    EVP_CIPHER_key_length(c), EVP_MD_size(h),
    3155             :                    EVP_CIPHER_iv_length(c));
    3156             :         return 2 * (EVP_CIPHER_key_length(c) + EVP_MD_size(h) +
    3157             :                     EVP_CIPHER_iv_length(c));
    3158             : #endif
    3159             : }
    3160             : #endif /* OPENSSL_NEED_EAP_FAST_PRF */
    3161             : 
    3162             : 
    3163        1043 : int tls_connection_export_key(void *tls_ctx, struct tls_connection *conn,
    3164             :                               const char *label, u8 *out, size_t out_len)
    3165             : {
    3166        2086 :         if (!conn ||
    3167        1043 :             SSL_export_keying_material(conn->ssl, out, out_len, label,
    3168             :                                        os_strlen(label), NULL, 0, 0) != 1)
    3169           0 :                 return -1;
    3170        1043 :         return 0;
    3171             : }
    3172             : 
    3173             : 
    3174         231 : int tls_connection_get_eap_fast_key(void *tls_ctx, struct tls_connection *conn,
    3175             :                                     u8 *out, size_t out_len)
    3176             : {
    3177             : #ifdef OPENSSL_NEED_EAP_FAST_PRF
    3178             :         SSL *ssl;
    3179             :         SSL_SESSION *sess;
    3180             :         u8 *rnd;
    3181         231 :         int ret = -1;
    3182         231 :         int skip = 0;
    3183         231 :         u8 *tmp_out = NULL;
    3184         231 :         u8 *_out = out;
    3185             :         unsigned char client_random[SSL3_RANDOM_SIZE];
    3186             :         unsigned char server_random[SSL3_RANDOM_SIZE];
    3187             :         unsigned char master_key[64];
    3188             :         size_t master_key_len;
    3189             :         const char *ver;
    3190             : 
    3191             :         /*
    3192             :          * TLS library did not support EAP-FAST key generation, so get the
    3193             :          * needed TLS session parameters and use an internal implementation of
    3194             :          * TLS PRF to derive the key.
    3195             :          */
    3196             : 
    3197         231 :         if (conn == NULL)
    3198           0 :                 return -1;
    3199         231 :         ssl = conn->ssl;
    3200         231 :         if (ssl == NULL)
    3201           0 :                 return -1;
    3202         231 :         ver = SSL_get_version(ssl);
    3203         231 :         sess = SSL_get_session(ssl);
    3204         231 :         if (!ver || !sess)
    3205           0 :                 return -1;
    3206             : 
    3207         231 :         skip = openssl_get_keyblock_size(ssl);
    3208         231 :         if (skip < 0)
    3209           0 :                 return -1;
    3210         231 :         tmp_out = os_malloc(skip + out_len);
    3211         231 :         if (!tmp_out)
    3212           0 :                 return -1;
    3213         231 :         _out = tmp_out;
    3214             : 
    3215         231 :         rnd = os_malloc(2 * SSL3_RANDOM_SIZE);
    3216         231 :         if (!rnd) {
    3217           1 :                 os_free(tmp_out);
    3218           1 :                 return -1;
    3219             :         }
    3220             : 
    3221         230 :         SSL_get_client_random(ssl, client_random, sizeof(client_random));
    3222         230 :         SSL_get_server_random(ssl, server_random, sizeof(server_random));
    3223         230 :         master_key_len = SSL_SESSION_get_master_key(sess, master_key,
    3224             :                                                     sizeof(master_key));
    3225             : 
    3226         230 :         os_memcpy(rnd, server_random, SSL3_RANDOM_SIZE);
    3227         230 :         os_memcpy(rnd + SSL3_RANDOM_SIZE, client_random, SSL3_RANDOM_SIZE);
    3228             : 
    3229         230 :         if (os_strcmp(ver, "TLSv1.2") == 0) {
    3230           0 :                 tls_prf_sha256(master_key, master_key_len,
    3231             :                                "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
    3232             :                                _out, skip + out_len);
    3233           0 :                 ret = 0;
    3234         230 :         } else if (tls_prf_sha1_md5(master_key, master_key_len,
    3235             :                                     "key expansion", rnd, 2 * SSL3_RANDOM_SIZE,
    3236             :                                     _out, skip + out_len) == 0) {
    3237         230 :                 ret = 0;
    3238             :         }
    3239         230 :         os_memset(master_key, 0, sizeof(master_key));
    3240         230 :         os_free(rnd);
    3241         230 :         if (ret == 0)
    3242         230 :                 os_memcpy(out, _out + skip, out_len);
    3243         230 :         bin_clear_free(tmp_out, skip);
    3244             : 
    3245         230 :         return ret;
    3246             : #else /* OPENSSL_NEED_EAP_FAST_PRF */
    3247             :         wpa_printf(MSG_ERROR,
    3248             :                    "OpenSSL: EAP-FAST keys cannot be exported in FIPS mode");
    3249             :         return -1;
    3250             : #endif /* OPENSSL_NEED_EAP_FAST_PRF */
    3251             : }
    3252             : 
    3253             : 
    3254             : static struct wpabuf *
    3255        2807 : openssl_handshake(struct tls_connection *conn, const struct wpabuf *in_data,
    3256             :                   int server)
    3257             : {
    3258             :         int res;
    3259             :         struct wpabuf *out_data;
    3260             : 
    3261             :         /*
    3262             :          * Give TLS handshake data from the server (if available) to OpenSSL
    3263             :          * for processing.
    3264             :          */
    3265        5012 :         if (in_data && wpabuf_len(in_data) > 0 &&
    3266        2205 :             BIO_write(conn->ssl_in, wpabuf_head(in_data), wpabuf_len(in_data))
    3267             :             < 0) {
    3268           0 :                 tls_show_errors(MSG_INFO, __func__,
    3269             :                                 "Handshake failed - BIO_write");
    3270           0 :                 return NULL;
    3271             :         }
    3272             : 
    3273             :         /* Initiate TLS handshake or continue the existing handshake */
    3274        2807 :         if (server)
    3275        1120 :                 res = SSL_accept(conn->ssl);
    3276             :         else
    3277        1687 :                 res = SSL_connect(conn->ssl);
    3278        2807 :         if (res != 1) {
    3279        1741 :                 int err = SSL_get_error(conn->ssl, res);
    3280        1741 :                 if (err == SSL_ERROR_WANT_READ)
    3281        1674 :                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want "
    3282             :                                    "more data");
    3283          67 :                 else if (err == SSL_ERROR_WANT_WRITE)
    3284           0 :                         wpa_printf(MSG_DEBUG, "SSL: SSL_connect - want to "
    3285             :                                    "write");
    3286             :                 else {
    3287          67 :                         tls_show_errors(MSG_INFO, __func__, "SSL_connect");
    3288          67 :                         conn->failed++;
    3289             :                 }
    3290             :         }
    3291             : 
    3292             :         /* Get the TLS handshake data to be sent to the server */
    3293        2807 :         res = BIO_ctrl_pending(conn->ssl_out);
    3294        2807 :         wpa_printf(MSG_DEBUG, "SSL: %d bytes pending from ssl_out", res);
    3295        2807 :         out_data = wpabuf_alloc(res);
    3296        2807 :         if (out_data == NULL) {
    3297           0 :                 wpa_printf(MSG_DEBUG, "SSL: Failed to allocate memory for "
    3298             :                            "handshake output (%d bytes)", res);
    3299           0 :                 if (BIO_reset(conn->ssl_out) < 0) {
    3300           0 :                         tls_show_errors(MSG_INFO, __func__,
    3301             :                                         "BIO_reset failed");
    3302             :                 }
    3303           0 :                 return NULL;
    3304             :         }
    3305        2807 :         res = res == 0 ? 0 : BIO_read(conn->ssl_out, wpabuf_mhead(out_data),
    3306             :                                       res);
    3307        2807 :         if (res < 0) {
    3308           0 :                 tls_show_errors(MSG_INFO, __func__,
    3309             :                                 "Handshake failed - BIO_read");
    3310           0 :                 if (BIO_reset(conn->ssl_out) < 0) {
    3311           0 :                         tls_show_errors(MSG_INFO, __func__,
    3312             :                                         "BIO_reset failed");
    3313             :                 }
    3314           0 :                 wpabuf_free(out_data);
    3315           0 :                 return NULL;
    3316             :         }
    3317        2807 :         wpabuf_put(out_data, res);
    3318             : 
    3319        2807 :         return out_data;
    3320             : }
    3321             : 
    3322             : 
    3323             : static struct wpabuf *
    3324         546 : openssl_get_appl_data(struct tls_connection *conn, size_t max_len)
    3325             : {
    3326             :         struct wpabuf *appl_data;
    3327             :         int res;
    3328             : 
    3329         546 :         appl_data = wpabuf_alloc(max_len + 100);
    3330         546 :         if (appl_data == NULL)
    3331           0 :                 return NULL;
    3332             : 
    3333         546 :         res = SSL_read(conn->ssl, wpabuf_mhead(appl_data),
    3334         546 :                        wpabuf_size(appl_data));
    3335         546 :         if (res < 0) {
    3336         452 :                 int err = SSL_get_error(conn->ssl, res);
    3337         452 :                 if (err == SSL_ERROR_WANT_READ ||
    3338             :                     err == SSL_ERROR_WANT_WRITE) {
    3339         452 :                         wpa_printf(MSG_DEBUG, "SSL: No Application Data "
    3340             :                                    "included");
    3341             :                 } else {
    3342           0 :                         tls_show_errors(MSG_INFO, __func__,
    3343             :                                         "Failed to read possible "
    3344             :                                         "Application Data");
    3345             :                 }
    3346         452 :                 wpabuf_free(appl_data);
    3347         452 :                 return NULL;
    3348             :         }
    3349             : 
    3350          94 :         wpabuf_put(appl_data, res);
    3351          94 :         wpa_hexdump_buf_key(MSG_MSGDUMP, "SSL: Application Data in Finished "
    3352             :                             "message", appl_data);
    3353             : 
    3354          94 :         return appl_data;
    3355             : }
    3356             : 
    3357             : 
    3358             : static struct wpabuf *
    3359        2807 : openssl_connection_handshake(struct tls_connection *conn,
    3360             :                              const struct wpabuf *in_data,
    3361             :                              struct wpabuf **appl_data, int server)
    3362             : {
    3363             :         struct wpabuf *out_data;
    3364             : 
    3365        2807 :         if (appl_data)
    3366        1687 :                 *appl_data = NULL;
    3367             : 
    3368        2807 :         out_data = openssl_handshake(conn, in_data, server);
    3369        2807 :         if (out_data == NULL)
    3370           0 :                 return NULL;
    3371        2807 :         if (conn->invalid_hb_used) {
    3372           0 :                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
    3373           0 :                 wpabuf_free(out_data);
    3374           0 :                 return NULL;
    3375             :         }
    3376             : 
    3377        2807 :         if (SSL_is_init_finished(conn->ssl)) {
    3378        1066 :                 wpa_printf(MSG_DEBUG,
    3379             :                            "OpenSSL: Handshake finished - resumed=%d",
    3380        1066 :                            tls_connection_resumed(conn->ssl_ctx, conn));
    3381        1066 :                 if (appl_data && in_data)
    3382         546 :                         *appl_data = openssl_get_appl_data(conn,
    3383             :                                                            wpabuf_len(in_data));
    3384             :         }
    3385             : 
    3386        2807 :         if (conn->invalid_hb_used) {
    3387           0 :                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
    3388           0 :                 if (appl_data) {
    3389           0 :                         wpabuf_free(*appl_data);
    3390           0 :                         *appl_data = NULL;
    3391             :                 }
    3392           0 :                 wpabuf_free(out_data);
    3393           0 :                 return NULL;
    3394             :         }
    3395             : 
    3396        2807 :         return out_data;
    3397             : }
    3398             : 
    3399             : 
    3400             : struct wpabuf *
    3401        1687 : tls_connection_handshake(void *ssl_ctx, struct tls_connection *conn,
    3402             :                          const struct wpabuf *in_data,
    3403             :                          struct wpabuf **appl_data)
    3404             : {
    3405        1687 :         return openssl_connection_handshake(conn, in_data, appl_data, 0);
    3406             : }
    3407             : 
    3408             : 
    3409        1120 : struct wpabuf * tls_connection_server_handshake(void *tls_ctx,
    3410             :                                                 struct tls_connection *conn,
    3411             :                                                 const struct wpabuf *in_data,
    3412             :                                                 struct wpabuf **appl_data)
    3413             : {
    3414        1120 :         return openssl_connection_handshake(conn, in_data, appl_data, 1);
    3415             : }
    3416             : 
    3417             : 
    3418        2027 : struct wpabuf * tls_connection_encrypt(void *tls_ctx,
    3419             :                                        struct tls_connection *conn,
    3420             :                                        const struct wpabuf *in_data)
    3421             : {
    3422             :         int res;
    3423             :         struct wpabuf *buf;
    3424             : 
    3425        2027 :         if (conn == NULL)
    3426           0 :                 return NULL;
    3427             : 
    3428             :         /* Give plaintext data for OpenSSL to encrypt into the TLS tunnel. */
    3429        4054 :         if ((res = BIO_reset(conn->ssl_in)) < 0 ||
    3430        2027 :             (res = BIO_reset(conn->ssl_out)) < 0) {
    3431           0 :                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
    3432           0 :                 return NULL;
    3433             :         }
    3434        2027 :         res = SSL_write(conn->ssl, wpabuf_head(in_data), wpabuf_len(in_data));
    3435        2027 :         if (res < 0) {
    3436           0 :                 tls_show_errors(MSG_INFO, __func__,
    3437             :                                 "Encryption failed - SSL_write");
    3438           0 :                 return NULL;
    3439             :         }
    3440             : 
    3441             :         /* Read encrypted data to be sent to the server */
    3442        2027 :         buf = wpabuf_alloc(wpabuf_len(in_data) + 300);
    3443        2027 :         if (buf == NULL)
    3444           3 :                 return NULL;
    3445        2024 :         res = BIO_read(conn->ssl_out, wpabuf_mhead(buf), wpabuf_size(buf));
    3446        2024 :         if (res < 0) {
    3447           9 :                 tls_show_errors(MSG_INFO, __func__,
    3448             :                                 "Encryption failed - BIO_read");
    3449           9 :                 wpabuf_free(buf);
    3450           9 :                 return NULL;
    3451             :         }
    3452        2015 :         wpabuf_put(buf, res);
    3453             : 
    3454        2015 :         return buf;
    3455             : }
    3456             : 
    3457             : 
    3458        1909 : struct wpabuf * tls_connection_decrypt(void *tls_ctx,
    3459             :                                        struct tls_connection *conn,
    3460             :                                        const struct wpabuf *in_data)
    3461             : {
    3462             :         int res;
    3463             :         struct wpabuf *buf;
    3464             : 
    3465             :         /* Give encrypted data from TLS tunnel for OpenSSL to decrypt. */
    3466        1909 :         res = BIO_write(conn->ssl_in, wpabuf_head(in_data),
    3467        1909 :                         wpabuf_len(in_data));
    3468        1909 :         if (res < 0) {
    3469           0 :                 tls_show_errors(MSG_INFO, __func__,
    3470             :                                 "Decryption failed - BIO_write");
    3471           0 :                 return NULL;
    3472             :         }
    3473        1909 :         if (BIO_reset(conn->ssl_out) < 0) {
    3474           0 :                 tls_show_errors(MSG_INFO, __func__, "BIO_reset failed");
    3475           0 :                 return NULL;
    3476             :         }
    3477             : 
    3478             :         /* Read decrypted data for further processing */
    3479             :         /*
    3480             :          * Even though we try to disable TLS compression, it is possible that
    3481             :          * this cannot be done with all TLS libraries. Add extra buffer space
    3482             :          * to handle the possibility of the decrypted data being longer than
    3483             :          * input data.
    3484             :          */
    3485        1909 :         buf = wpabuf_alloc((wpabuf_len(in_data) + 500) * 3);
    3486        1909 :         if (buf == NULL)
    3487           1 :                 return NULL;
    3488        1908 :         res = SSL_read(conn->ssl, wpabuf_mhead(buf), wpabuf_size(buf));
    3489        1908 :         if (res < 0) {
    3490           2 :                 tls_show_errors(MSG_INFO, __func__,
    3491             :                                 "Decryption failed - SSL_read");
    3492           2 :                 wpabuf_free(buf);
    3493           2 :                 return NULL;
    3494             :         }
    3495        1906 :         wpabuf_put(buf, res);
    3496             : 
    3497        1906 :         if (conn->invalid_hb_used) {
    3498           0 :                 wpa_printf(MSG_INFO, "TLS: Heartbeat attack detected - do not send response");
    3499           0 :                 wpabuf_free(buf);
    3500           0 :                 return NULL;
    3501             :         }
    3502             : 
    3503        1906 :         return buf;
    3504             : }
    3505             : 
    3506             : 
    3507        3046 : int tls_connection_resumed(void *ssl_ctx, struct tls_connection *conn)
    3508             : {
    3509        3046 :         return conn ? SSL_cache_hit(conn->ssl) : 0;
    3510             : }
    3511             : 
    3512             : 
    3513         238 : int tls_connection_set_cipher_list(void *tls_ctx, struct tls_connection *conn,
    3514             :                                    u8 *ciphers)
    3515             : {
    3516             :         char buf[500], *pos, *end;
    3517             :         u8 *c;
    3518             :         int ret;
    3519             : 
    3520         238 :         if (conn == NULL || conn->ssl == NULL || ciphers == NULL)
    3521           0 :                 return -1;
    3522             : 
    3523         238 :         buf[0] = '\0';
    3524         238 :         pos = buf;
    3525         238 :         end = pos + sizeof(buf);
    3526             : 
    3527         238 :         c = ciphers;
    3528        1527 :         while (*c != TLS_CIPHER_NONE) {
    3529             :                 const char *suite;
    3530             : 
    3531        1051 :                 switch (*c) {
    3532             :                 case TLS_CIPHER_RC4_SHA:
    3533         168 :                         suite = "RC4-SHA";
    3534         168 :                         break;
    3535             :                 case TLS_CIPHER_AES128_SHA:
    3536         168 :                         suite = "AES128-SHA";
    3537         168 :                         break;
    3538             :                 case TLS_CIPHER_RSA_DHE_AES128_SHA:
    3539         168 :                         suite = "DHE-RSA-AES128-SHA";
    3540         168 :                         break;
    3541             :                 case TLS_CIPHER_ANON_DH_AES128_SHA:
    3542         211 :                         suite = "ADH-AES128-SHA";
    3543         211 :                         break;
    3544             :                 case TLS_CIPHER_RSA_DHE_AES256_SHA:
    3545         168 :                         suite = "DHE-RSA-AES256-SHA";
    3546         168 :                         break;
    3547             :                 case TLS_CIPHER_AES256_SHA:
    3548         168 :                         suite = "AES256-SHA";
    3549         168 :                         break;
    3550             :                 default:
    3551           0 :                         wpa_printf(MSG_DEBUG, "TLS: Unsupported "
    3552           0 :                                    "cipher selection: %d", *c);
    3553           0 :                         return -1;
    3554             :                 }
    3555        1051 :                 ret = os_snprintf(pos, end - pos, ":%s", suite);
    3556        1051 :                 if (os_snprintf_error(end - pos, ret))
    3557           0 :                         break;
    3558        1051 :                 pos += ret;
    3559             : 
    3560        1051 :                 c++;
    3561             :         }
    3562             : 
    3563         238 :         wpa_printf(MSG_DEBUG, "OpenSSL: cipher suites: %s", buf + 1);
    3564             : 
    3565             : #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
    3566             : #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
    3567             :         if (os_strstr(buf, ":ADH-")) {
    3568             :                 /*
    3569             :                  * Need to drop to security level 0 to allow anonymous
    3570             :                  * cipher suites for EAP-FAST.
    3571             :                  */
    3572             :                 SSL_set_security_level(conn->ssl, 0);
    3573             :         } else if (SSL_get_security_level(conn->ssl) == 0) {
    3574             :                 /* Force at least security level 1 */
    3575             :                 SSL_set_security_level(conn->ssl, 1);
    3576             :         }
    3577             : #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
    3578             : #endif
    3579             : 
    3580         238 :         if (SSL_set_cipher_list(conn->ssl, buf + 1) != 1) {
    3581           0 :                 tls_show_errors(MSG_INFO, __func__,
    3582             :                                 "Cipher suite configuration failed");
    3583           0 :                 return -1;
    3584             :         }
    3585             : 
    3586         238 :         return 0;
    3587             : }
    3588             : 
    3589             : 
    3590         617 : int tls_get_version(void *ssl_ctx, struct tls_connection *conn,
    3591             :                     char *buf, size_t buflen)
    3592             : {
    3593             :         const char *name;
    3594         617 :         if (conn == NULL || conn->ssl == NULL)
    3595           0 :                 return -1;
    3596             : 
    3597         617 :         name = SSL_get_version(conn->ssl);
    3598         617 :         if (name == NULL)
    3599           0 :                 return -1;
    3600             : 
    3601         617 :         os_strlcpy(buf, name, buflen);
    3602         617 :         return 0;
    3603             : }
    3604             : 
    3605             : 
    3606         746 : int tls_get_cipher(void *ssl_ctx, struct tls_connection *conn,
    3607             :                    char *buf, size_t buflen)
    3608             : {
    3609             :         const char *name;
    3610         746 :         if (conn == NULL || conn->ssl == NULL)
    3611           0 :                 return -1;
    3612             : 
    3613         746 :         name = SSL_get_cipher(conn->ssl);
    3614         746 :         if (name == NULL)
    3615           0 :                 return -1;
    3616             : 
    3617         746 :         os_strlcpy(buf, name, buflen);
    3618         746 :         return 0;
    3619             : }
    3620             : 
    3621             : 
    3622         165 : int tls_connection_enable_workaround(void *ssl_ctx,
    3623             :                                      struct tls_connection *conn)
    3624             : {
    3625         165 :         SSL_set_options(conn->ssl, SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS);
    3626             : 
    3627         165 :         return 0;
    3628             : }
    3629             : 
    3630             : 
    3631             : #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
    3632             : /* ClientHello TLS extensions require a patch to openssl, so this function is
    3633             :  * commented out unless explicitly needed for EAP-FAST in order to be able to
    3634             :  * build this file with unmodified openssl. */
    3635         134 : int tls_connection_client_hello_ext(void *ssl_ctx, struct tls_connection *conn,
    3636             :                                     int ext_type, const u8 *data,
    3637             :                                     size_t data_len)
    3638             : {
    3639         134 :         if (conn == NULL || conn->ssl == NULL || ext_type != 35)
    3640           0 :                 return -1;
    3641             : 
    3642         134 :         if (SSL_set_session_ticket_ext(conn->ssl, (void *) data,
    3643             :                                        data_len) != 1)
    3644           0 :                 return -1;
    3645             : 
    3646         134 :         return 0;
    3647             : }
    3648             : #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
    3649             : 
    3650             : 
    3651        2982 : int tls_connection_get_failed(void *ssl_ctx, struct tls_connection *conn)
    3652             : {
    3653        2982 :         if (conn == NULL)
    3654           0 :                 return -1;
    3655        2982 :         return conn->failed;
    3656             : }
    3657             : 
    3658             : 
    3659           0 : int tls_connection_get_read_alerts(void *ssl_ctx, struct tls_connection *conn)
    3660             : {
    3661           0 :         if (conn == NULL)
    3662           0 :                 return -1;
    3663           0 :         return conn->read_alerts;
    3664             : }
    3665             : 
    3666             : 
    3667        2425 : int tls_connection_get_write_alerts(void *ssl_ctx, struct tls_connection *conn)
    3668             : {
    3669        2425 :         if (conn == NULL)
    3670           0 :                 return -1;
    3671        2425 :         return conn->write_alerts;
    3672             : }
    3673             : 
    3674             : 
    3675             : #ifdef HAVE_OCSP
    3676             : 
    3677          12 : static void ocsp_debug_print_resp(OCSP_RESPONSE *rsp)
    3678             : {
    3679             : #ifndef CONFIG_NO_STDOUT_DEBUG
    3680             :         BIO *out;
    3681             :         size_t rlen;
    3682             :         char *txt;
    3683             :         int res;
    3684             : 
    3685          12 :         if (wpa_debug_level > MSG_DEBUG)
    3686           0 :                 return;
    3687             : 
    3688          12 :         out = BIO_new(BIO_s_mem());
    3689          12 :         if (!out)
    3690           0 :                 return;
    3691             : 
    3692          12 :         OCSP_RESPONSE_print(out, rsp, 0);
    3693          12 :         rlen = BIO_ctrl_pending(out);
    3694          12 :         txt = os_malloc(rlen + 1);
    3695          12 :         if (!txt) {
    3696           0 :                 BIO_free(out);
    3697           0 :                 return;
    3698             :         }
    3699             : 
    3700          12 :         res = BIO_read(out, txt, rlen);
    3701          12 :         if (res > 0) {
    3702          12 :                 txt[res] = '\0';
    3703          12 :                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP Response\n%s", txt);
    3704             :         }
    3705          12 :         os_free(txt);
    3706          12 :         BIO_free(out);
    3707             : #endif /* CONFIG_NO_STDOUT_DEBUG */
    3708             : }
    3709             : 
    3710             : 
    3711          12 : static void debug_print_cert(X509 *cert, const char *title)
    3712             : {
    3713             : #ifndef CONFIG_NO_STDOUT_DEBUG
    3714             :         BIO *out;
    3715             :         size_t rlen;
    3716             :         char *txt;
    3717             :         int res;
    3718             : 
    3719          12 :         if (wpa_debug_level > MSG_DEBUG)
    3720           0 :                 return;
    3721             : 
    3722          12 :         out = BIO_new(BIO_s_mem());
    3723          12 :         if (!out)
    3724           0 :                 return;
    3725             : 
    3726          12 :         X509_print(out, cert);
    3727          12 :         rlen = BIO_ctrl_pending(out);
    3728          12 :         txt = os_malloc(rlen + 1);
    3729          12 :         if (!txt) {
    3730           0 :                 BIO_free(out);
    3731           0 :                 return;
    3732             :         }
    3733             : 
    3734          12 :         res = BIO_read(out, txt, rlen);
    3735          12 :         if (res > 0) {
    3736          12 :                 txt[res] = '\0';
    3737          12 :                 wpa_printf(MSG_DEBUG, "OpenSSL: %s\n%s", title, txt);
    3738             :         }
    3739          12 :         os_free(txt);
    3740             : 
    3741          12 :         BIO_free(out);
    3742             : #endif /* CONFIG_NO_STDOUT_DEBUG */
    3743             : }
    3744             : 
    3745             : 
    3746          14 : static int ocsp_resp_cb(SSL *s, void *arg)
    3747             : {
    3748          14 :         struct tls_connection *conn = arg;
    3749             :         const unsigned char *p;
    3750             :         int len, status, reason;
    3751             :         OCSP_RESPONSE *rsp;
    3752             :         OCSP_BASICRESP *basic;
    3753             :         OCSP_CERTID *id;
    3754             :         ASN1_GENERALIZEDTIME *produced_at, *this_update, *next_update;
    3755             :         X509_STORE *store;
    3756          14 :         STACK_OF(X509) *certs = NULL;
    3757             : 
    3758          14 :         len = SSL_get_tlsext_status_ocsp_resp(s, &p);
    3759          14 :         if (!p) {
    3760           1 :                 wpa_printf(MSG_DEBUG, "OpenSSL: No OCSP response received");
    3761           1 :                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
    3762             :         }
    3763             : 
    3764          13 :         wpa_hexdump(MSG_DEBUG, "OpenSSL: OCSP response", p, len);
    3765             : 
    3766          13 :         rsp = d2i_OCSP_RESPONSE(NULL, &p, len);
    3767          13 :         if (!rsp) {
    3768           1 :                 wpa_printf(MSG_INFO, "OpenSSL: Failed to parse OCSP response");
    3769           1 :                 return 0;
    3770             :         }
    3771             : 
    3772          12 :         ocsp_debug_print_resp(rsp);
    3773             : 
    3774          12 :         status = OCSP_response_status(rsp);
    3775          12 :         if (status != OCSP_RESPONSE_STATUS_SUCCESSFUL) {
    3776           0 :                 wpa_printf(MSG_INFO, "OpenSSL: OCSP responder error %d (%s)",
    3777             :                            status, OCSP_response_status_str(status));
    3778           0 :                 return 0;
    3779             :         }
    3780             : 
    3781          12 :         basic = OCSP_response_get1_basic(rsp);
    3782          12 :         if (!basic) {
    3783           0 :                 wpa_printf(MSG_INFO, "OpenSSL: Could not find BasicOCSPResponse");
    3784           0 :                 return 0;
    3785             :         }
    3786             : 
    3787          12 :         store = SSL_CTX_get_cert_store(conn->ssl_ctx);
    3788          12 :         if (conn->peer_issuer) {
    3789          12 :                 debug_print_cert(conn->peer_issuer, "Add OCSP issuer");
    3790             : 
    3791          12 :                 if (X509_STORE_add_cert(store, conn->peer_issuer) != 1) {
    3792          10 :                         tls_show_errors(MSG_INFO, __func__,
    3793             :                                         "OpenSSL: Could not add issuer to certificate store");
    3794             :                 }
    3795          12 :                 certs = sk_X509_new_null();
    3796          12 :                 if (certs) {
    3797             :                         X509 *cert;
    3798          12 :                         cert = X509_dup(conn->peer_issuer);
    3799          12 :                         if (cert && !sk_X509_push(certs, cert)) {
    3800           0 :                                 tls_show_errors(
    3801             :                                         MSG_INFO, __func__,
    3802             :                                         "OpenSSL: Could not add issuer to OCSP responder trust store");
    3803           0 :                                 X509_free(cert);
    3804           0 :                                 sk_X509_free(certs);
    3805           0 :                                 certs = NULL;
    3806             :                         }
    3807          12 :                         if (certs && conn->peer_issuer_issuer) {
    3808           2 :                                 cert = X509_dup(conn->peer_issuer_issuer);
    3809           2 :                                 if (cert && !sk_X509_push(certs, cert)) {
    3810           0 :                                         tls_show_errors(
    3811             :                                                 MSG_INFO, __func__,
    3812             :                                                 "OpenSSL: Could not add issuer's issuer to OCSP responder trust store");
    3813           0 :                                         X509_free(cert);
    3814             :                                 }
    3815             :                         }
    3816             :                 }
    3817             :         }
    3818             : 
    3819          12 :         status = OCSP_basic_verify(basic, certs, store, OCSP_TRUSTOTHER);
    3820          12 :         sk_X509_pop_free(certs, X509_free);
    3821          12 :         if (status <= 0) {
    3822           1 :                 tls_show_errors(MSG_INFO, __func__,
    3823             :                                 "OpenSSL: OCSP response failed verification");
    3824           1 :                 OCSP_BASICRESP_free(basic);
    3825           1 :                 OCSP_RESPONSE_free(rsp);
    3826           1 :                 return 0;
    3827             :         }
    3828             : 
    3829          11 :         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP response verification succeeded");
    3830             : 
    3831          11 :         if (!conn->peer_cert) {
    3832           0 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer certificate not available for OCSP status check");
    3833           0 :                 OCSP_BASICRESP_free(basic);
    3834           0 :                 OCSP_RESPONSE_free(rsp);
    3835           0 :                 return 0;
    3836             :         }
    3837             : 
    3838          11 :         if (!conn->peer_issuer) {
    3839           0 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Peer issuer certificate not available for OCSP status check");
    3840           0 :                 OCSP_BASICRESP_free(basic);
    3841           0 :                 OCSP_RESPONSE_free(rsp);
    3842           0 :                 return 0;
    3843             :         }
    3844             : 
    3845          11 :         id = OCSP_cert_to_id(NULL, conn->peer_cert, conn->peer_issuer);
    3846          11 :         if (!id) {
    3847           0 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Could not create OCSP certificate identifier");
    3848           0 :                 OCSP_BASICRESP_free(basic);
    3849           0 :                 OCSP_RESPONSE_free(rsp);
    3850           0 :                 return 0;
    3851             :         }
    3852             : 
    3853          11 :         if (!OCSP_resp_find_status(basic, id, &status, &reason, &produced_at,
    3854             :                                    &this_update, &next_update)) {
    3855           1 :                 wpa_printf(MSG_INFO, "OpenSSL: Could not find current server certificate from OCSP response%s",
    3856           1 :                            (conn->flags & TLS_CONN_REQUIRE_OCSP) ? "" :
    3857             :                            " (OCSP not required)");
    3858           1 :                 OCSP_CERTID_free(id);
    3859           1 :                 OCSP_BASICRESP_free(basic);
    3860           1 :                 OCSP_RESPONSE_free(rsp);
    3861           1 :                 return (conn->flags & TLS_CONN_REQUIRE_OCSP) ? 0 : 1;
    3862             :         }
    3863          10 :         OCSP_CERTID_free(id);
    3864             : 
    3865          10 :         if (!OCSP_check_validity(this_update, next_update, 5 * 60, -1)) {
    3866           0 :                 tls_show_errors(MSG_INFO, __func__,
    3867             :                                 "OpenSSL: OCSP status times invalid");
    3868           0 :                 OCSP_BASICRESP_free(basic);
    3869           0 :                 OCSP_RESPONSE_free(rsp);
    3870           0 :                 return 0;
    3871             :         }
    3872             : 
    3873          10 :         OCSP_BASICRESP_free(basic);
    3874          10 :         OCSP_RESPONSE_free(rsp);
    3875             : 
    3876          10 :         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status for server certificate: %s",
    3877             :                    OCSP_cert_status_str(status));
    3878             : 
    3879          10 :         if (status == V_OCSP_CERTSTATUS_GOOD)
    3880           4 :                 return 1;
    3881           6 :         if (status == V_OCSP_CERTSTATUS_REVOKED)
    3882           1 :                 return 0;
    3883           5 :         if (conn->flags & TLS_CONN_REQUIRE_OCSP) {
    3884           4 :                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP required");
    3885           4 :                 return 0;
    3886             :         }
    3887           1 :         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status unknown, but OCSP was not required, so allow connection to continue");
    3888           1 :         return 1;
    3889             : }
    3890             : 
    3891             : 
    3892          14 : static int ocsp_status_cb(SSL *s, void *arg)
    3893             : {
    3894             :         char *tmp;
    3895             :         char *resp;
    3896             :         size_t len;
    3897             : 
    3898          14 :         if (tls_global->ocsp_stapling_response == NULL) {
    3899           0 :                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - no response configured");
    3900           0 :                 return SSL_TLSEXT_ERR_OK;
    3901             :         }
    3902             : 
    3903          14 :         resp = os_readfile(tls_global->ocsp_stapling_response, &len);
    3904          14 :         if (resp == NULL) {
    3905           1 :                 wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - could not read response file");
    3906             :                 /* TODO: Build OCSPResponse with responseStatus = internalError
    3907             :                  */
    3908           1 :                 return SSL_TLSEXT_ERR_OK;
    3909             :         }
    3910          13 :         wpa_printf(MSG_DEBUG, "OpenSSL: OCSP status callback - send cached response");
    3911          13 :         tmp = OPENSSL_malloc(len);
    3912          13 :         if (tmp == NULL) {
    3913           0 :                 os_free(resp);
    3914           0 :                 return SSL_TLSEXT_ERR_ALERT_FATAL;
    3915             :         }
    3916             : 
    3917          13 :         os_memcpy(tmp, resp, len);
    3918          13 :         os_free(resp);
    3919          13 :         SSL_set_tlsext_status_ocsp_resp(s, tmp, len);
    3920             : 
    3921          13 :         return SSL_TLSEXT_ERR_OK;
    3922             : }
    3923             : 
    3924             : #endif /* HAVE_OCSP */
    3925             : 
    3926             : 
    3927         602 : int tls_connection_set_params(void *tls_ctx, struct tls_connection *conn,
    3928             :                               const struct tls_connection_params *params)
    3929             : {
    3930         602 :         struct tls_data *data = tls_ctx;
    3931             :         int ret;
    3932             :         unsigned long err;
    3933         602 :         int can_pkcs11 = 0;
    3934         602 :         const char *key_id = params->key_id;
    3935         602 :         const char *cert_id = params->cert_id;
    3936         602 :         const char *ca_cert_id = params->ca_cert_id;
    3937         602 :         const char *engine_id = params->engine ? params->engine_id : NULL;
    3938             : 
    3939         602 :         if (conn == NULL)
    3940           0 :                 return -1;
    3941             : 
    3942         602 :         if (params->flags & TLS_CONN_REQUIRE_OCSP_ALL) {
    3943           0 :                 wpa_printf(MSG_INFO,
    3944             :                            "OpenSSL: ocsp=3 not supported");
    3945           0 :                 return -1;
    3946             :         }
    3947             : 
    3948             :         /*
    3949             :          * If the engine isn't explicitly configured, and any of the
    3950             :          * cert/key fields are actually PKCS#11 URIs, then automatically
    3951             :          * use the PKCS#11 ENGINE.
    3952             :          */
    3953         602 :         if (!engine_id || os_strcmp(engine_id, "pkcs11") == 0)
    3954         602 :                 can_pkcs11 = 1;
    3955             : 
    3956         679 :         if (!key_id && params->private_key && can_pkcs11 &&
    3957          77 :             os_strncmp(params->private_key, "pkcs11:", 7) == 0) {
    3958           0 :                 can_pkcs11 = 2;
    3959           0 :                 key_id = params->private_key;
    3960             :         }
    3961             : 
    3962         656 :         if (!cert_id && params->client_cert && can_pkcs11 &&
    3963          54 :             os_strncmp(params->client_cert, "pkcs11:", 7) == 0) {
    3964           0 :                 can_pkcs11 = 2;
    3965           0 :                 cert_id = params->client_cert;
    3966             :         }
    3967             : 
    3968        1177 :         if (!ca_cert_id && params->ca_cert && can_pkcs11 &&
    3969         575 :             os_strncmp(params->ca_cert, "pkcs11:", 7) == 0) {
    3970           0 :                 can_pkcs11 = 2;
    3971           0 :                 ca_cert_id = params->ca_cert;
    3972             :         }
    3973             : 
    3974             :         /* If we need to automatically enable the PKCS#11 ENGINE, do so. */
    3975         602 :         if (can_pkcs11 == 2 && !engine_id)
    3976           0 :                 engine_id = "pkcs11";
    3977             : 
    3978             : #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
    3979             : #if OPENSSL_VERSION_NUMBER < 0x10100000L
    3980         602 :         if (params->flags & TLS_CONN_EAP_FAST) {
    3981         165 :                 wpa_printf(MSG_DEBUG,
    3982             :                            "OpenSSL: Use TLSv1_method() for EAP-FAST");
    3983         165 :                 if (SSL_set_ssl_method(conn->ssl, TLSv1_method()) != 1) {
    3984           0 :                         tls_show_errors(MSG_INFO, __func__,
    3985             :                                         "Failed to set TLSv1_method() for EAP-FAST");
    3986           0 :                         return -1;
    3987             :                 }
    3988             :         }
    3989             : #endif
    3990             : #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
    3991             : 
    3992        1205 :         while ((err = ERR_get_error())) {
    3993           1 :                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
    3994             :                            __func__, ERR_error_string(err, NULL));
    3995             :         }
    3996             : 
    3997         602 :         if (engine_id) {
    3998           0 :                 wpa_printf(MSG_DEBUG, "SSL: Initializing TLS engine");
    3999           0 :                 ret = tls_engine_init(conn, engine_id, params->pin,
    4000             :                                       key_id, cert_id, ca_cert_id);
    4001           0 :                 if (ret)
    4002           0 :                         return ret;
    4003             :         }
    4004         602 :         if (tls_connection_set_subject_match(conn,
    4005             :                                              params->subject_match,
    4006             :                                              params->altsubject_match,
    4007             :                                              params->suffix_match,
    4008             :                                              params->domain_match))
    4009           4 :                 return -1;
    4010             : 
    4011         598 :         if (engine_id && ca_cert_id) {
    4012           0 :                 if (tls_connection_engine_ca_cert(data, conn, ca_cert_id))
    4013           0 :                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
    4014         598 :         } else if (tls_connection_ca_cert(data, conn, params->ca_cert,
    4015             :                                           params->ca_cert_blob,
    4016             :                                           params->ca_cert_blob_len,
    4017             :                                           params->ca_path))
    4018           3 :                 return -1;
    4019             : 
    4020         595 :         if (engine_id && cert_id) {
    4021           0 :                 if (tls_connection_engine_client_cert(conn, cert_id))
    4022           0 :                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
    4023         595 :         } else if (tls_connection_client_cert(conn, params->client_cert,
    4024             :                                               params->client_cert_blob,
    4025             :                                               params->client_cert_blob_len))
    4026           0 :                 return -1;
    4027             : 
    4028         595 :         if (engine_id && key_id) {
    4029           0 :                 wpa_printf(MSG_DEBUG, "TLS: Using private key from engine");
    4030           0 :                 if (tls_connection_engine_private_key(conn))
    4031           0 :                         return TLS_SET_PARAMS_ENGINE_PRV_VERIFY_FAILED;
    4032         595 :         } else if (tls_connection_private_key(data, conn,
    4033             :                                               params->private_key,
    4034             :                                               params->private_key_passwd,
    4035             :                                               params->private_key_blob,
    4036             :                                               params->private_key_blob_len)) {
    4037           1 :                 wpa_printf(MSG_INFO, "TLS: Failed to load private key '%s'",
    4038             :                            params->private_key);
    4039           1 :                 return -1;
    4040             :         }
    4041             : 
    4042         594 :         if (tls_connection_dh(conn, params->dh_file)) {
    4043           0 :                 wpa_printf(MSG_INFO, "TLS: Failed to load DH file '%s'",
    4044             :                            params->dh_file);
    4045           0 :                 return -1;
    4046             :         }
    4047             : 
    4048         612 :         if (params->openssl_ciphers &&
    4049          18 :             SSL_set_cipher_list(conn->ssl, params->openssl_ciphers) != 1) {
    4050           1 :                 wpa_printf(MSG_INFO,
    4051             :                            "OpenSSL: Failed to set cipher string '%s'",
    4052             :                            params->openssl_ciphers);
    4053           1 :                 return -1;
    4054             :         }
    4055             : 
    4056         593 :         tls_set_conn_flags(conn->ssl, params->flags);
    4057             : 
    4058             : #ifdef OPENSSL_IS_BORINGSSL
    4059             :         if (params->flags & TLS_CONN_REQUEST_OCSP) {
    4060             :                 SSL_enable_ocsp_stapling(conn->ssl);
    4061             :         }
    4062             : #else /* OPENSSL_IS_BORINGSSL */
    4063             : #ifdef HAVE_OCSP
    4064         593 :         if (params->flags & TLS_CONN_REQUEST_OCSP) {
    4065          14 :                 SSL_CTX *ssl_ctx = data->ssl;
    4066          14 :                 SSL_set_tlsext_status_type(conn->ssl, TLSEXT_STATUSTYPE_ocsp);
    4067          14 :                 SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_resp_cb);
    4068          14 :                 SSL_CTX_set_tlsext_status_arg(ssl_ctx, conn);
    4069             :         }
    4070             : #else /* HAVE_OCSP */
    4071             :         if (params->flags & TLS_CONN_REQUIRE_OCSP) {
    4072             :                 wpa_printf(MSG_INFO,
    4073             :                            "OpenSSL: No OCSP support included - reject configuration");
    4074             :                 return -1;
    4075             :         }
    4076             :         if (params->flags & TLS_CONN_REQUEST_OCSP) {
    4077             :                 wpa_printf(MSG_DEBUG,
    4078             :                            "OpenSSL: No OCSP support included - allow optional OCSP case to continue");
    4079             :         }
    4080             : #endif /* HAVE_OCSP */
    4081             : #endif /* OPENSSL_IS_BORINGSSL */
    4082             : 
    4083         593 :         conn->flags = params->flags;
    4084             : 
    4085         593 :         tls_get_errors(data);
    4086             : 
    4087         593 :         return 0;
    4088             : }
    4089             : 
    4090             : 
    4091         130 : int tls_global_set_params(void *tls_ctx,
    4092             :                           const struct tls_connection_params *params)
    4093             : {
    4094         130 :         struct tls_data *data = tls_ctx;
    4095         130 :         SSL_CTX *ssl_ctx = data->ssl;
    4096             :         unsigned long err;
    4097             : 
    4098         260 :         while ((err = ERR_get_error())) {
    4099           0 :                 wpa_printf(MSG_INFO, "%s: Clearing pending SSL error: %s",
    4100             :                            __func__, ERR_error_string(err, NULL));
    4101             :         }
    4102             : 
    4103         260 :         if (tls_global_ca_cert(data, params->ca_cert) ||
    4104         260 :             tls_global_client_cert(data, params->client_cert) ||
    4105         130 :             tls_global_private_key(data, params->private_key,
    4106         130 :                                    params->private_key_passwd) ||
    4107         130 :             tls_global_dh(data, params->dh_file)) {
    4108           2 :                 wpa_printf(MSG_INFO, "TLS: Failed to set global parameters");
    4109           2 :                 return -1;
    4110             :         }
    4111             : 
    4112         138 :         if (params->openssl_ciphers &&
    4113          10 :             SSL_CTX_set_cipher_list(ssl_ctx, params->openssl_ciphers) != 1) {
    4114           1 :                 wpa_printf(MSG_INFO,
    4115             :                            "OpenSSL: Failed to set cipher string '%s'",
    4116             :                            params->openssl_ciphers);
    4117           1 :                 return -1;
    4118             :         }
    4119             : 
    4120             : #ifdef SSL_OP_NO_TICKET
    4121         127 :         if (params->flags & TLS_CONN_DISABLE_SESSION_TICKET)
    4122           0 :                 SSL_CTX_set_options(ssl_ctx, SSL_OP_NO_TICKET);
    4123             : #ifdef SSL_CTX_clear_options
    4124             :         else
    4125         127 :                 SSL_CTX_clear_options(ssl_ctx, SSL_OP_NO_TICKET);
    4126             : #endif /* SSL_clear_options */
    4127             : #endif /*  SSL_OP_NO_TICKET */
    4128             : 
    4129             : #ifdef HAVE_OCSP
    4130         127 :         SSL_CTX_set_tlsext_status_cb(ssl_ctx, ocsp_status_cb);
    4131         127 :         SSL_CTX_set_tlsext_status_arg(ssl_ctx, ssl_ctx);
    4132         127 :         os_free(tls_global->ocsp_stapling_response);
    4133         127 :         if (params->ocsp_stapling_response)
    4134          50 :                 tls_global->ocsp_stapling_response =
    4135          25 :                         os_strdup(params->ocsp_stapling_response);
    4136             :         else
    4137         102 :                 tls_global->ocsp_stapling_response = NULL;
    4138             : #endif /* HAVE_OCSP */
    4139             : 
    4140         127 :         return 0;
    4141             : }
    4142             : 
    4143             : 
    4144             : #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
    4145             : /* Pre-shared secred requires a patch to openssl, so this function is
    4146             :  * commented out unless explicitly needed for EAP-FAST in order to be able to
    4147             :  * build this file with unmodified openssl. */
    4148             : 
    4149             : #if (defined(OPENSSL_IS_BORINGSSL) || OPENSSL_VERSION_NUMBER >= 0x10100000L) && !defined(LIBRESSL_VERSION_NUMBER)
    4150             : static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
    4151             :                            STACK_OF(SSL_CIPHER) *peer_ciphers,
    4152             :                            const SSL_CIPHER **cipher, void *arg)
    4153             : #else /* OPENSSL_IS_BORINGSSL */
    4154         236 : static int tls_sess_sec_cb(SSL *s, void *secret, int *secret_len,
    4155             :                            STACK_OF(SSL_CIPHER) *peer_ciphers,
    4156             :                            SSL_CIPHER **cipher, void *arg)
    4157             : #endif /* OPENSSL_IS_BORINGSSL */
    4158             : {
    4159         236 :         struct tls_connection *conn = arg;
    4160             :         int ret;
    4161             : 
    4162             : #if OPENSSL_VERSION_NUMBER < 0x10100000L || defined(LIBRESSL_VERSION_NUMBER)
    4163         236 :         if (conn == NULL || conn->session_ticket_cb == NULL)
    4164           0 :                 return 0;
    4165             : 
    4166         708 :         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
    4167         236 :                                       conn->session_ticket,
    4168             :                                       conn->session_ticket_len,
    4169         236 :                                       s->s3->client_random,
    4170         236 :                                       s->s3->server_random, secret);
    4171             : #else
    4172             :         unsigned char client_random[SSL3_RANDOM_SIZE];
    4173             :         unsigned char server_random[SSL3_RANDOM_SIZE];
    4174             : 
    4175             :         if (conn == NULL || conn->session_ticket_cb == NULL)
    4176             :                 return 0;
    4177             : 
    4178             :         SSL_get_client_random(s, client_random, sizeof(client_random));
    4179             :         SSL_get_server_random(s, server_random, sizeof(server_random));
    4180             : 
    4181             :         ret = conn->session_ticket_cb(conn->session_ticket_cb_ctx,
    4182             :                                       conn->session_ticket,
    4183             :                                       conn->session_ticket_len,
    4184             :                                       client_random,
    4185             :                                       server_random, secret);
    4186             : #endif
    4187             : 
    4188         236 :         os_free(conn->session_ticket);
    4189         236 :         conn->session_ticket = NULL;
    4190             : 
    4191         236 :         if (ret <= 0)
    4192         164 :                 return 0;
    4193             : 
    4194          72 :         *secret_len = SSL_MAX_MASTER_KEY_LENGTH;
    4195          72 :         return 1;
    4196             : }
    4197             : 
    4198             : 
    4199          37 : static int tls_session_ticket_ext_cb(SSL *s, const unsigned char *data,
    4200             :                                      int len, void *arg)
    4201             : {
    4202          37 :         struct tls_connection *conn = arg;
    4203             : 
    4204          37 :         if (conn == NULL || conn->session_ticket_cb == NULL)
    4205           0 :                 return 0;
    4206             : 
    4207          37 :         wpa_printf(MSG_DEBUG, "OpenSSL: %s: length=%d", __func__, len);
    4208             : 
    4209          37 :         os_free(conn->session_ticket);
    4210          37 :         conn->session_ticket = NULL;
    4211             : 
    4212          37 :         wpa_hexdump(MSG_DEBUG, "OpenSSL: ClientHello SessionTicket "
    4213             :                     "extension", data, len);
    4214             : 
    4215          37 :         conn->session_ticket = os_malloc(len);
    4216          37 :         if (conn->session_ticket == NULL)
    4217           1 :                 return 0;
    4218             : 
    4219          36 :         os_memcpy(conn->session_ticket, data, len);
    4220          36 :         conn->session_ticket_len = len;
    4221             : 
    4222          36 :         return 1;
    4223             : }
    4224             : #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
    4225             : 
    4226             : 
    4227         306 : int tls_connection_set_session_ticket_cb(void *tls_ctx,
    4228             :                                          struct tls_connection *conn,
    4229             :                                          tls_session_ticket_cb cb,
    4230             :                                          void *ctx)
    4231             : {
    4232             : #if defined(EAP_FAST) || defined(EAP_FAST_DYNAMIC) || defined(EAP_SERVER_FAST)
    4233         306 :         conn->session_ticket_cb = cb;
    4234         306 :         conn->session_ticket_cb_ctx = ctx;
    4235             : 
    4236         306 :         if (cb) {
    4237         306 :                 if (SSL_set_session_secret_cb(conn->ssl, tls_sess_sec_cb,
    4238             :                                               conn) != 1)
    4239           0 :                         return -1;
    4240         306 :                 SSL_set_session_ticket_ext_cb(conn->ssl,
    4241             :                                               tls_session_ticket_ext_cb, conn);
    4242             :         } else {
    4243           0 :                 if (SSL_set_session_secret_cb(conn->ssl, NULL, NULL) != 1)
    4244           0 :                         return -1;
    4245           0 :                 SSL_set_session_ticket_ext_cb(conn->ssl, NULL, NULL);
    4246             :         }
    4247             : 
    4248         306 :         return 0;
    4249             : #else /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
    4250             :         return -1;
    4251             : #endif /* EAP_FAST || EAP_FAST_DYNAMIC || EAP_SERVER_FAST */
    4252             : }
    4253             : 
    4254             : 
    4255          88 : int tls_get_library_version(char *buf, size_t buf_len)
    4256             : {
    4257             : #if OPENSSL_VERSION_NUMBER >= 0x10100000L && !defined(LIBRESSL_VERSION_NUMBER)
    4258             :         return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
    4259             :                            OPENSSL_VERSION_TEXT,
    4260             :                            OpenSSL_version(OPENSSL_VERSION));
    4261             : #else
    4262          88 :         return os_snprintf(buf, buf_len, "OpenSSL build=%s run=%s",
    4263             :                            OPENSSL_VERSION_TEXT,
    4264             :                            SSLeay_version(SSLEAY_VERSION));
    4265             : #endif
    4266             : }
    4267             : 
    4268             : 
    4269          11 : void tls_connection_set_success_data(struct tls_connection *conn,
    4270             :                                      struct wpabuf *data)
    4271             : {
    4272             :         SSL_SESSION *sess;
    4273             :         struct wpabuf *old;
    4274             : 
    4275          11 :         if (tls_ex_idx_session < 0)
    4276           0 :                 goto fail;
    4277          11 :         sess = SSL_get_session(conn->ssl);
    4278          11 :         if (!sess)
    4279           0 :                 goto fail;
    4280          11 :         old = SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
    4281          11 :         if (old) {
    4282           0 :                 wpa_printf(MSG_DEBUG, "OpenSSL: Replacing old success data %p",
    4283             :                            old);
    4284           0 :                 wpabuf_free(old);
    4285             :         }
    4286          11 :         if (SSL_SESSION_set_ex_data(sess, tls_ex_idx_session, data) != 1)
    4287           0 :                 goto fail;
    4288             : 
    4289          11 :         wpa_printf(MSG_DEBUG, "OpenSSL: Stored success data %p", data);
    4290          11 :         conn->success_data = 1;
    4291          22 :         return;
    4292             : 
    4293             : fail:
    4294           0 :         wpa_printf(MSG_INFO, "OpenSSL: Failed to store success data");
    4295           0 :         wpabuf_free(data);
    4296             : }
    4297             : 
    4298             : 
    4299          10 : void tls_connection_set_success_data_resumed(struct tls_connection *conn)
    4300             : {
    4301          10 :         wpa_printf(MSG_DEBUG,
    4302             :                    "OpenSSL: Success data accepted for resumed session");
    4303          10 :         conn->success_data = 1;
    4304          10 : }
    4305             : 
    4306             : 
    4307             : const struct wpabuf *
    4308          11 : tls_connection_get_success_data(struct tls_connection *conn)
    4309             : {
    4310             :         SSL_SESSION *sess;
    4311             : 
    4312          22 :         if (tls_ex_idx_session < 0 ||
    4313          11 :             !(sess = SSL_get_session(conn->ssl)))
    4314           0 :                 return NULL;
    4315          11 :         return SSL_SESSION_get_ex_data(sess, tls_ex_idx_session);
    4316             : }
    4317             : 
    4318             : 
    4319          65 : void tls_connection_remove_session(struct tls_connection *conn)
    4320             : {
    4321             :         SSL_SESSION *sess;
    4322             : 
    4323          65 :         sess = SSL_get_session(conn->ssl);
    4324          65 :         if (!sess)
    4325          66 :                 return;
    4326             : 
    4327          64 :         if (SSL_CTX_remove_session(conn->ssl_ctx, sess) != 1)
    4328          64 :                 wpa_printf(MSG_DEBUG,
    4329             :                            "OpenSSL: Session was not cached");
    4330             :         else
    4331           0 :                 wpa_printf(MSG_DEBUG,
    4332             :                            "OpenSSL: Removed cached session to disable session resumption");
    4333             : }

Generated by: LCOV version 1.10