Home | History | Annotate | Download | only in ssl
      1 /* Copyright (C) 1995-1998 Eric Young (eay (at) cryptsoft.com)
      2  * All rights reserved.
      3  *
      4  * This package is an SSL implementation written
      5  * by Eric Young (eay (at) cryptsoft.com).
      6  * The implementation was written so as to conform with Netscapes SSL.
      7  *
      8  * This library is free for commercial and non-commercial use as long as
      9  * the following conditions are aheared to.  The following conditions
     10  * apply to all code found in this distribution, be it the RC4, RSA,
     11  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
     12  * included with this distribution is covered by the same copyright terms
     13  * except that the holder is Tim Hudson (tjh (at) cryptsoft.com).
     14  *
     15  * Copyright remains Eric Young's, and as such any Copyright notices in
     16  * the code are not to be removed.
     17  * If this package is used in a product, Eric Young should be given attribution
     18  * as the author of the parts of the library used.
     19  * This can be in the form of a textual message at program startup or
     20  * in documentation (online or textual) provided with the package.
     21  *
     22  * Redistribution and use in source and binary forms, with or without
     23  * modification, are permitted provided that the following conditions
     24  * are met:
     25  * 1. Redistributions of source code must retain the copyright
     26  *    notice, this list of conditions and the following disclaimer.
     27  * 2. Redistributions in binary form must reproduce the above copyright
     28  *    notice, this list of conditions and the following disclaimer in the
     29  *    documentation and/or other materials provided with the distribution.
     30  * 3. All advertising materials mentioning features or use of this software
     31  *    must display the following acknowledgement:
     32  *    "This product includes cryptographic software written by
     33  *     Eric Young (eay (at) cryptsoft.com)"
     34  *    The word 'cryptographic' can be left out if the rouines from the library
     35  *    being used are not cryptographic related :-).
     36  * 4. If you include any Windows specific code (or a derivative thereof) from
     37  *    the apps directory (application code) you must include an acknowledgement:
     38  *    "This product includes software written by Tim Hudson (tjh (at) cryptsoft.com)"
     39  *
     40  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
     41  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
     43  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
     44  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
     45  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
     46  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     47  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
     48  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     49  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     50  * SUCH DAMAGE.
     51  *
     52  * The licence and distribution terms for any publically available version or
     53  * derivative of this code cannot be changed.  i.e. this code cannot simply be
     54  * copied and put under another distribution licence
     55  * [including the GNU Public Licence.]
     56  */
     57 /* ====================================================================
     58  * Copyright (c) 1998-2007 The OpenSSL Project.  All rights reserved.
     59  *
     60  * Redistribution and use in source and binary forms, with or without
     61  * modification, are permitted provided that the following conditions
     62  * are met:
     63  *
     64  * 1. Redistributions of source code must retain the above copyright
     65  *    notice, this list of conditions and the following disclaimer.
     66  *
     67  * 2. Redistributions in binary form must reproduce the above copyright
     68  *    notice, this list of conditions and the following disclaimer in
     69  *    the documentation and/or other materials provided with the
     70  *    distribution.
     71  *
     72  * 3. All advertising materials mentioning features or use of this
     73  *    software must display the following acknowledgment:
     74  *    "This product includes software developed by the OpenSSL Project
     75  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
     76  *
     77  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
     78  *    endorse or promote products derived from this software without
     79  *    prior written permission. For written permission, please contact
     80  *    openssl-core (at) openssl.org.
     81  *
     82  * 5. Products derived from this software may not be called "OpenSSL"
     83  *    nor may "OpenSSL" appear in their names without prior written
     84  *    permission of the OpenSSL Project.
     85  *
     86  * 6. Redistributions of any form whatsoever must retain the following
     87  *    acknowledgment:
     88  *    "This product includes software developed by the OpenSSL Project
     89  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
     90  *
     91  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
     92  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
     93  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
     94  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
     95  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
     96  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
     97  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     98  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
     99  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
    100  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    101  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
    102  * OF THE POSSIBILITY OF SUCH DAMAGE.
    103  * ====================================================================
    104  *
    105  * This product includes cryptographic software written by Eric Young
    106  * (eay (at) cryptsoft.com).  This product includes software written by Tim
    107  * Hudson (tjh (at) cryptsoft.com).
    108  *
    109  */
    110 /* ====================================================================
    111  * Copyright 2005 Nokia. All rights reserved.
    112  *
    113  * The portions of the attached software ("Contribution") is developed by
    114  * Nokia Corporation and is licensed pursuant to the OpenSSL open source
    115  * license.
    116  *
    117  * The Contribution, originally written by Mika Kousa and Pasi Eronen of
    118  * Nokia Corporation, consists of the "PSK" (Pre-Shared Key) ciphersuites
    119  * support (see RFC 4279) to OpenSSL.
    120  *
    121  * No patent licenses or other rights except those expressly stated in
    122  * the OpenSSL open source license shall be deemed granted or received
    123  * expressly, by implication, estoppel, or otherwise.
    124  *
    125  * No assurances are provided by Nokia that the Contribution does not
    126  * infringe the patent or other intellectual property rights of any third
    127  * party or that the license provides you with all the necessary rights
    128  * to make use of the Contribution.
    129  *
    130  * THE SOFTWARE IS PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND. IN
    131  * ADDITION TO THE DISCLAIMERS INCLUDED IN THE LICENSE, NOKIA
    132  * SPECIFICALLY DISCLAIMS ANY LIABILITY FOR CLAIMS BROUGHT BY YOU OR ANY
    133  * OTHER ENTITY BASED ON INFRINGEMENT OF INTELLECTUAL PROPERTY RIGHTS OR
    134  * OTHERWISE. */
    135 
    136 #include <openssl/ssl.h>
    137 
    138 #include <assert.h>
    139 #include <string.h>
    140 
    141 #include <utility>
    142 
    143 #include <openssl/err.h>
    144 #include <openssl/evp.h>
    145 #include <openssl/hmac.h>
    146 #include <openssl/md5.h>
    147 #include <openssl/mem.h>
    148 #include <openssl/nid.h>
    149 #include <openssl/rand.h>
    150 
    151 #include "../crypto/fipsmodule/tls/internal.h"
    152 #include "../crypto/internal.h"
    153 #include "internal.h"
    154 
    155 
    156 namespace bssl {
    157 
    158 bool tls1_prf(const EVP_MD *digest, Span<uint8_t> out,
    159               Span<const uint8_t> secret, Span<const char> label,
    160               Span<const uint8_t> seed1, Span<const uint8_t> seed2) {
    161   return 1 == CRYPTO_tls1_prf(digest, out.data(), out.size(), secret.data(),
    162                               secret.size(), label.data(), label.size(),
    163                               seed1.data(), seed1.size(), seed2.data(),
    164                               seed2.size());
    165 }
    166 
    167 static bool ssl3_prf(Span<uint8_t> out, Span<const uint8_t> secret,
    168                      Span<const char> label, Span<const uint8_t> seed1,
    169                      Span<const uint8_t> seed2) {
    170   ScopedEVP_MD_CTX md5;
    171   ScopedEVP_MD_CTX sha1;
    172   uint8_t buf[16], smd[SHA_DIGEST_LENGTH];
    173   uint8_t c = 'A';
    174   size_t k = 0;
    175   while (!out.empty()) {
    176     k++;
    177     if (k > sizeof(buf)) {
    178       // bug: 'buf' is too small for this ciphersuite
    179       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    180       return false;
    181     }
    182 
    183     for (size_t j = 0; j < k; j++) {
    184       buf[j] = c;
    185     }
    186     c++;
    187     if (!EVP_DigestInit_ex(sha1.get(), EVP_sha1(), NULL)) {
    188       OPENSSL_PUT_ERROR(SSL, ERR_LIB_EVP);
    189       return false;
    190     }
    191     EVP_DigestUpdate(sha1.get(), buf, k);
    192     EVP_DigestUpdate(sha1.get(), secret.data(), secret.size());
    193     // |label| is ignored for SSLv3.
    194     EVP_DigestUpdate(sha1.get(), seed1.data(), seed1.size());
    195     EVP_DigestUpdate(sha1.get(), seed2.data(), seed2.size());
    196     EVP_DigestFinal_ex(sha1.get(), smd, NULL);
    197 
    198     if (!EVP_DigestInit_ex(md5.get(), EVP_md5(), NULL)) {
    199       OPENSSL_PUT_ERROR(SSL, ERR_LIB_EVP);
    200       return false;
    201     }
    202     EVP_DigestUpdate(md5.get(), secret.data(), secret.size());
    203     EVP_DigestUpdate(md5.get(), smd, SHA_DIGEST_LENGTH);
    204     if (out.size() < MD5_DIGEST_LENGTH) {
    205       EVP_DigestFinal_ex(md5.get(), smd, NULL);
    206       OPENSSL_memcpy(out.data(), smd, out.size());
    207       break;
    208     }
    209     EVP_DigestFinal_ex(md5.get(), out.data(), NULL);
    210     out = out.subspan(MD5_DIGEST_LENGTH);
    211   }
    212 
    213   OPENSSL_cleanse(smd, SHA_DIGEST_LENGTH);
    214   return true;
    215 }
    216 
    217 static bool get_key_block_lengths(const SSL *ssl, size_t *out_mac_secret_len,
    218                                   size_t *out_key_len, size_t *out_iv_len,
    219                                   const SSL_CIPHER *cipher) {
    220   const EVP_AEAD *aead = NULL;
    221   if (!ssl_cipher_get_evp_aead(&aead, out_mac_secret_len, out_iv_len, cipher,
    222                                ssl_protocol_version(ssl), SSL_is_dtls(ssl))) {
    223     OPENSSL_PUT_ERROR(SSL, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
    224     return false;
    225   }
    226 
    227   *out_key_len = EVP_AEAD_key_length(aead);
    228   if (*out_mac_secret_len > 0) {
    229     // For "stateful" AEADs (i.e. compatibility with pre-AEAD cipher suites) the
    230     // key length reported by |EVP_AEAD_key_length| will include the MAC key
    231     // bytes and initial implicit IV.
    232     if (*out_key_len < *out_mac_secret_len + *out_iv_len) {
    233       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
    234       return false;
    235     }
    236     *out_key_len -= *out_mac_secret_len + *out_iv_len;
    237   }
    238 
    239   return true;
    240 }
    241 
    242 int tls1_configure_aead(SSL *ssl, evp_aead_direction_t direction,
    243                         Array<uint8_t> *key_block_cache,
    244                         const SSL_CIPHER *cipher,
    245                         Span<const uint8_t> iv_override) {
    246   size_t mac_secret_len, key_len, iv_len;
    247   if (!get_key_block_lengths(ssl, &mac_secret_len, &key_len, &iv_len, cipher)) {
    248     return 0;
    249   }
    250 
    251   // Ensure that |key_block_cache| is set up.
    252   const size_t key_block_size = 2 * (mac_secret_len + key_len + iv_len);
    253   if (key_block_cache->empty()) {
    254     if (!key_block_cache->Init(key_block_size) ||
    255         !SSL_generate_key_block(ssl, key_block_cache->data(), key_block_size)) {
    256       return 0;
    257     }
    258   }
    259   assert(key_block_cache->size() == key_block_size);
    260 
    261   Span<const uint8_t> key_block = *key_block_cache;
    262   Span<const uint8_t> mac_secret, key, iv;
    263   if (direction == (ssl->server ? evp_aead_open : evp_aead_seal)) {
    264     // Use the client write (server read) keys.
    265     mac_secret = key_block.subspan(0, mac_secret_len);
    266     key = key_block.subspan(2 * mac_secret_len, key_len);
    267     iv = key_block.subspan(2 * mac_secret_len + 2 * key_len, iv_len);
    268   } else {
    269     // Use the server write (client read) keys.
    270     mac_secret = key_block.subspan(mac_secret_len, mac_secret_len);
    271     key = key_block.subspan(2 * mac_secret_len + key_len, key_len);
    272     iv = key_block.subspan(2 * mac_secret_len + 2 * key_len + iv_len, iv_len);
    273   }
    274 
    275   if (!iv_override.empty()) {
    276     if (iv_override.size() != iv_len) {
    277       return 0;
    278     }
    279     iv = iv_override;
    280   }
    281 
    282   UniquePtr<SSLAEADContext> aead_ctx = SSLAEADContext::Create(
    283       direction, ssl->version, SSL_is_dtls(ssl), cipher, key, mac_secret, iv);
    284   if (!aead_ctx) {
    285     return 0;
    286   }
    287 
    288   if (direction == evp_aead_open) {
    289     return ssl->method->set_read_state(ssl, std::move(aead_ctx));
    290   }
    291 
    292   return ssl->method->set_write_state(ssl, std::move(aead_ctx));
    293 }
    294 
    295 int tls1_change_cipher_state(SSL_HANDSHAKE *hs,
    296                              evp_aead_direction_t direction) {
    297   return tls1_configure_aead(hs->ssl, direction, &hs->key_block,
    298                              hs->new_cipher, {});
    299 }
    300 
    301 int tls1_generate_master_secret(SSL_HANDSHAKE *hs, uint8_t *out,
    302                                 Span<const uint8_t> premaster) {
    303   static const char kMasterSecretLabel[] = "master secret";
    304   static const char kExtendedMasterSecretLabel[] = "extended master secret";
    305 
    306   const SSL *ssl = hs->ssl;
    307   auto out_span = MakeSpan(out, SSL3_MASTER_SECRET_SIZE);
    308   if (hs->extended_master_secret) {
    309     auto label = MakeConstSpan(kExtendedMasterSecretLabel,
    310                                sizeof(kExtendedMasterSecretLabel) - 1);
    311     uint8_t digests[EVP_MAX_MD_SIZE];
    312     size_t digests_len;
    313     if (!hs->transcript.GetHash(digests, &digests_len) ||
    314         !tls1_prf(hs->transcript.Digest(), out_span, premaster, label,
    315                   MakeConstSpan(digests, digests_len), {})) {
    316       return 0;
    317     }
    318   } else {
    319     auto label =
    320         MakeConstSpan(kMasterSecretLabel, sizeof(kMasterSecretLabel) - 1);
    321     if (ssl_protocol_version(ssl) == SSL3_VERSION) {
    322       if (!ssl3_prf(out_span, premaster, label, ssl->s3->client_random,
    323                     ssl->s3->server_random)) {
    324         return 0;
    325       }
    326     } else {
    327       if (!tls1_prf(hs->transcript.Digest(), out_span, premaster, label,
    328                     ssl->s3->client_random, ssl->s3->server_random)) {
    329         return 0;
    330       }
    331     }
    332   }
    333 
    334   return SSL3_MASTER_SECRET_SIZE;
    335 }
    336 
    337 }  // namespace bssl
    338 
    339 using namespace bssl;
    340 
    341 size_t SSL_get_key_block_len(const SSL *ssl) {
    342   size_t mac_secret_len, key_len, fixed_iv_len;
    343   if (!get_key_block_lengths(ssl, &mac_secret_len, &key_len, &fixed_iv_len,
    344                              SSL_get_current_cipher(ssl))) {
    345     ERR_clear_error();
    346     return 0;
    347   }
    348 
    349   return 2 * (mac_secret_len + key_len + fixed_iv_len);
    350 }
    351 
    352 int SSL_generate_key_block(const SSL *ssl, uint8_t *out, size_t out_len) {
    353   const SSL_SESSION *session = SSL_get_session(ssl);
    354   auto out_span = MakeSpan(out, out_len);
    355   auto master_key =
    356       MakeConstSpan(session->master_key, session->master_key_length);
    357   static const char kLabel[] = "key expansion";
    358   auto label = MakeConstSpan(kLabel, sizeof(kLabel) - 1);
    359 
    360   if (ssl_protocol_version(ssl) == SSL3_VERSION) {
    361     return ssl3_prf(out_span, master_key, label, ssl->s3->server_random,
    362                     ssl->s3->client_random);
    363   }
    364 
    365   const EVP_MD *digest = ssl_session_get_digest(session);
    366   return tls1_prf(digest, out_span, master_key, label, ssl->s3->server_random,
    367                   ssl->s3->client_random);
    368 }
    369 
    370 int SSL_export_keying_material(SSL *ssl, uint8_t *out, size_t out_len,
    371                                const char *label, size_t label_len,
    372                                const uint8_t *context, size_t context_len,
    373                                int use_context) {
    374   if (!ssl->s3->have_version || ssl->version == SSL3_VERSION) {
    375     OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_NOT_COMPLETE);
    376     return 0;
    377   }
    378 
    379   // Exporters may be used in False Start and server 0-RTT, where the handshake
    380   // has progressed enough. Otherwise, they may not be used during a handshake.
    381   if (SSL_in_init(ssl) &&
    382       !SSL_in_false_start(ssl) &&
    383       !(SSL_is_server(ssl) && SSL_in_early_data(ssl))) {
    384     OPENSSL_PUT_ERROR(SSL, SSL_R_HANDSHAKE_NOT_COMPLETE);
    385     return 0;
    386   }
    387 
    388   if (ssl_protocol_version(ssl) >= TLS1_3_VERSION) {
    389     if (!use_context) {
    390       context = nullptr;
    391       context_len = 0;
    392     }
    393     return tls13_export_keying_material(
    394         ssl, MakeSpan(out, out_len),
    395         MakeConstSpan(ssl->s3->exporter_secret, ssl->s3->exporter_secret_len),
    396         MakeConstSpan(label, label_len), MakeConstSpan(context, context_len));
    397   }
    398 
    399   size_t seed_len = 2 * SSL3_RANDOM_SIZE;
    400   if (use_context) {
    401     if (context_len >= 1u << 16) {
    402       OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
    403       return 0;
    404     }
    405     seed_len += 2 + context_len;
    406   }
    407   Array<uint8_t> seed;
    408   if (!seed.Init(seed_len)) {
    409     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
    410     return 0;
    411   }
    412 
    413   OPENSSL_memcpy(seed.data(), ssl->s3->client_random, SSL3_RANDOM_SIZE);
    414   OPENSSL_memcpy(seed.data() + SSL3_RANDOM_SIZE, ssl->s3->server_random,
    415                  SSL3_RANDOM_SIZE);
    416   if (use_context) {
    417     seed[2 * SSL3_RANDOM_SIZE] = static_cast<uint8_t>(context_len >> 8);
    418     seed[2 * SSL3_RANDOM_SIZE + 1] = static_cast<uint8_t>(context_len);
    419     OPENSSL_memcpy(seed.data() + 2 * SSL3_RANDOM_SIZE + 2, context, context_len);
    420   }
    421 
    422   const SSL_SESSION *session = SSL_get_session(ssl);
    423   const EVP_MD *digest = ssl_session_get_digest(session);
    424   return tls1_prf(
    425       digest, MakeSpan(out, out_len),
    426       MakeConstSpan(session->master_key, session->master_key_length),
    427       MakeConstSpan(label, label_len), seed, {});
    428 }
    429 
    430 int SSL_export_early_keying_material(
    431     SSL *ssl, uint8_t *out, size_t out_len, const char *label, size_t label_len,
    432     const uint8_t *context, size_t context_len) {
    433   if (!SSL_in_early_data(ssl) &&
    434       (!ssl->s3->have_version ||
    435        ssl_protocol_version(ssl) < TLS1_3_VERSION)) {
    436     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_SSL_VERSION);
    437     return 0;
    438   }
    439 
    440   // The early exporter only exists if we accepted early data or offered it as
    441   // a client.
    442   if (!SSL_in_early_data(ssl) && !SSL_early_data_accepted(ssl)) {
    443     OPENSSL_PUT_ERROR(SSL, SSL_R_EARLY_DATA_NOT_IN_USE);
    444     return 0;
    445   }
    446 
    447   return tls13_export_keying_material(
    448       ssl, MakeSpan(out, out_len),
    449       MakeConstSpan(ssl->s3->early_exporter_secret,
    450                     ssl->s3->early_exporter_secret_len),
    451       MakeConstSpan(label, label_len), MakeConstSpan(context, context_len));
    452 }
    453