tls13_enc.c 35.6 KB
Newer Older
1
/*
M
Matt Caswell 已提交
2
 * Copyright 2016-2020 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5 6 7 8 9 10
 * this file except in compliance with the License.  You can obtain a copy
 * in the file LICENSE in the source distribution or at
 * https://www.openssl.org/source/license.html
 */

#include <stdlib.h>
11
#include "ssl_local.h"
12
#include "internal/cryptlib.h"
13 14
#include <openssl/evp.h>
#include <openssl/kdf.h>
P
Pauli 已提交
15
#include <openssl/core_names.h>
16

17
#define TLS13_MAX_LABEL_LEN     249
18 19 20 21 22

/* Always filled with zeros */
static const unsigned char default_zeros[EVP_MAX_MD_SIZE];

/*
23 24 25
 * Given a |secret|; a |label| of length |labellen|; and |data| of length
 * |datalen| (e.g. typically a hash of the handshake messages), derive a new
 * secret |outlen| bytes long and store it in the location pointed to be |out|.
26 27
 * The |data| value may be zero length. Any errors will be treated as fatal if
 * |fatal| is set. Returns 1 on success  0 on failure.
28
 */
29
int tls13_hkdf_expand(SSL *s, const EVP_MD *md, const unsigned char *secret,
30
                             const unsigned char *label, size_t labellen,
31
                             const unsigned char *data, size_t datalen,
32
                             unsigned char *out, size_t outlen, int fatal)
33
{
O
opensslonzos-github 已提交
34 35 36
#ifdef CHARSET_EBCDIC
    static const unsigned char label_prefix[] = { 0x74, 0x6C, 0x73, 0x31, 0x33, 0x20, 0x00 };
#else
37
    static const unsigned char label_prefix[] = "tls13 ";
O
opensslonzos-github 已提交
38
#endif
39 40
    EVP_KDF *kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_HKDF,
                                 s->ctx->propq);
P
Pauli 已提交
41 42 43 44
    EVP_KDF_CTX *kctx;
    OSSL_PARAM params[5], *p = params;
    int mode = EVP_PKEY_HKDEF_MODE_EXPAND_ONLY;
    const char *mdname = EVP_MD_name(md);
45 46 47 48
    int ret;
    size_t hkdflabellen;
    size_t hashlen;
    /*
49 50 51
     * 2 bytes for length of derived secret + 1 byte for length of combined
     * prefix and label + bytes for the label itself + 1 byte length of hash
     * + bytes for the hash itself
52
     */
D
dcruette 已提交
53
    unsigned char hkdflabel[sizeof(uint16_t) + sizeof(uint8_t)
54
                            + (sizeof(label_prefix) - 1) + TLS13_MAX_LABEL_LEN
55
                            + 1 + EVP_MAX_MD_SIZE];
56 57
    WPACKET pkt;

P
Pauli 已提交
58 59
    kctx = EVP_KDF_CTX_new(kdf);
    EVP_KDF_free(kdf);
60
    if (kctx == NULL)
61 62
        return 0;

63 64 65 66 67 68 69 70 71 72 73
    if (labellen > TLS13_MAX_LABEL_LEN) {
        if (fatal) {
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_HKDF_EXPAND,
                     ERR_R_INTERNAL_ERROR);
        } else {
            /*
             * Probably we have been called from SSL_export_keying_material(),
             * or SSL_export_keying_material_early().
             */
            SSLerr(SSL_F_TLS13_HKDF_EXPAND, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
        }
74
        EVP_KDF_CTX_free(kctx);
75 76 77
        return 0;
    }

78 79 80 81 82 83 84 85
    hashlen = EVP_MD_size(md);

    if (!WPACKET_init_static_len(&pkt, hkdflabel, sizeof(hkdflabel), 0)
            || !WPACKET_put_bytes_u16(&pkt, outlen)
            || !WPACKET_start_sub_packet_u8(&pkt)
            || !WPACKET_memcpy(&pkt, label_prefix, sizeof(label_prefix) - 1)
            || !WPACKET_memcpy(&pkt, label, labellen)
            || !WPACKET_close(&pkt)
86
            || !WPACKET_sub_memcpy_u8(&pkt, data, (data == NULL) ? 0 : datalen)
87 88
            || !WPACKET_get_total_written(&pkt, &hkdflabellen)
            || !WPACKET_finish(&pkt)) {
89
        EVP_KDF_CTX_free(kctx);
90
        WPACKET_cleanup(&pkt);
91 92 93 94 95
        if (fatal)
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_HKDF_EXPAND,
                     ERR_R_INTERNAL_ERROR);
        else
            SSLerr(SSL_F_TLS13_HKDF_EXPAND, ERR_R_INTERNAL_ERROR);
96 97 98
        return 0;
    }

P
Pauli 已提交
99 100
    *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
    *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
101
                                            (char *)mdname, 0);
P
Pauli 已提交
102 103 104 105 106 107 108
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
                                             (unsigned char *)secret, hashlen);
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_INFO,
                                             hkdflabel, hkdflabellen);
    *p++ = OSSL_PARAM_construct_end();

    ret = EVP_KDF_CTX_set_params(kctx, params) <= 0
109
        || EVP_KDF_derive(kctx, out, outlen) <= 0;
110

111
    EVP_KDF_CTX_free(kctx);
112

113 114 115 116 117 118 119
    if (ret != 0) {
        if (fatal)
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_HKDF_EXPAND,
                     ERR_R_INTERNAL_ERROR);
        else
            SSLerr(SSL_F_TLS13_HKDF_EXPAND, ERR_R_INTERNAL_ERROR);
    }
120

121 122 123 124
    return ret == 0;
}

/*
125 126
 * Given a |secret| generate a |key| of length |keylen| bytes. Returns 1 on
 * success  0 on failure.
127
 */
128 129
int tls13_derive_key(SSL *s, const EVP_MD *md, const unsigned char *secret,
                     unsigned char *key, size_t keylen)
130
{
O
opensslonzos-github 已提交
131 132 133 134 135
#ifdef CHARSET_EBCDIC
  static const unsigned char keylabel[] ={ 0x6B, 0x65, 0x79, 0x00 };
#else
  static const unsigned char keylabel[] = "key";
#endif
136

137
    return tls13_hkdf_expand(s, md, secret, keylabel, sizeof(keylabel) - 1,
138
                             NULL, 0, key, keylen, 1);
139 140 141
}

/*
142 143
 * Given a |secret| generate an |iv| of length |ivlen| bytes. Returns 1 on
 * success  0 on failure.
144
 */
145 146
int tls13_derive_iv(SSL *s, const EVP_MD *md, const unsigned char *secret,
                    unsigned char *iv, size_t ivlen)
147
{
O
opensslonzos-github 已提交
148 149 150 151 152
#ifdef CHARSET_EBCDIC
  static const unsigned char ivlabel[] = { 0x69, 0x76, 0x00 };
#else
  static const unsigned char ivlabel[] = "iv";
#endif
153

154
    return tls13_hkdf_expand(s, md, secret, ivlabel, sizeof(ivlabel) - 1,
155
                             NULL, 0, iv, ivlen, 1);
156 157
}

158 159 160
int tls13_derive_finishedkey(SSL *s, const EVP_MD *md,
                             const unsigned char *secret,
                             unsigned char *fin, size_t finlen)
M
Matt Caswell 已提交
161
{
O
opensslonzos-github 已提交
162 163 164 165 166
#ifdef CHARSET_EBCDIC
  static const unsigned char finishedlabel[] = { 0x66, 0x69, 0x6E, 0x69, 0x73, 0x68, 0x65, 0x64, 0x00 };
#else
  static const unsigned char finishedlabel[] = "finished";
#endif
167

168
    return tls13_hkdf_expand(s, md, secret, finishedlabel,
169
                             sizeof(finishedlabel) - 1, NULL, 0, fin, finlen, 1);
M
Matt Caswell 已提交
170 171
}

172 173 174
/*
 * Given the previous secret |prevsecret| and a new input secret |insecret| of
 * length |insecretlen|, generate a new secret and store it in the location
175
 * pointed to by |outsecret|. Returns 1 on success  0 on failure.
176
 */
177 178 179 180 181
int tls13_generate_secret(SSL *s, const EVP_MD *md,
                          const unsigned char *prevsecret,
                          const unsigned char *insecret,
                          size_t insecretlen,
                          unsigned char *outsecret)
182 183
{
    size_t mdlen, prevsecretlen;
M
Matt Caswell 已提交
184
    int mdleni;
185
    int ret;
P
Pauli 已提交
186 187 188 189 190
    EVP_KDF *kdf;
    EVP_KDF_CTX *kctx;
    OSSL_PARAM params[5], *p = params;
    int mode = EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY;
    const char *mdname = EVP_MD_name(md);
O
opensslonzos-github 已提交
191 192 193
#ifdef CHARSET_EBCDIC
    static const char derived_secret_label[] = { 0x64, 0x65, 0x72, 0x69, 0x76, 0x65, 0x64, 0x00 };
#else
194
    static const char derived_secret_label[] = "derived";
O
opensslonzos-github 已提交
195
#endif
196
    unsigned char preextractsec[EVP_MAX_MD_SIZE];
197

198
    kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_HKDF, s->ctx->propq);
P
Pauli 已提交
199 200
    kctx = EVP_KDF_CTX_new(kdf);
    EVP_KDF_free(kdf);
201
    if (kctx == NULL) {
202 203
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_GENERATE_SECRET,
                 ERR_R_INTERNAL_ERROR);
204
        return 0;
205
    }
206

M
Matt Caswell 已提交
207 208 209 210 211
    mdleni = EVP_MD_size(md);
    /* Ensure cast to size_t is safe */
    if (!ossl_assert(mdleni >= 0)) {
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_GENERATE_SECRET,
                 ERR_R_INTERNAL_ERROR);
S
Shane Lontis 已提交
212
        EVP_KDF_CTX_free(kctx);
M
Matt Caswell 已提交
213 214 215
        return 0;
    }
    mdlen = (size_t)mdleni;
216 217 218 219 220 221 222 223 224

    if (insecret == NULL) {
        insecret = default_zeros;
        insecretlen = mdlen;
    }
    if (prevsecret == NULL) {
        prevsecret = default_zeros;
        prevsecretlen = 0;
    } else {
225 226 227 228 229 230 231
        EVP_MD_CTX *mctx = EVP_MD_CTX_new();
        unsigned char hash[EVP_MAX_MD_SIZE];

        /* The pre-extract derive step uses a hash of no messages */
        if (mctx == NULL
                || EVP_DigestInit_ex(mctx, md, NULL) <= 0
                || EVP_DigestFinal_ex(mctx, hash, NULL) <= 0) {
232 233
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_GENERATE_SECRET,
                     ERR_R_INTERNAL_ERROR);
234
            EVP_MD_CTX_free(mctx);
235
            EVP_KDF_CTX_free(kctx);
236 237 238 239 240 241 242
            return 0;
        }
        EVP_MD_CTX_free(mctx);

        /* Generate the pre-extract secret */
        if (!tls13_hkdf_expand(s, md, prevsecret,
                               (unsigned char *)derived_secret_label,
243
                               sizeof(derived_secret_label) - 1, hash, mdlen,
244
                               preextractsec, mdlen, 1)) {
245
            /* SSLfatal() already called */
246
            EVP_KDF_CTX_free(kctx);
247
            return 0;
248
        }
249 250

        prevsecret = preextractsec;
251 252 253
        prevsecretlen = mdlen;
    }

P
Pauli 已提交
254 255
    *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
    *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
256
                                            (char *)mdname, 0);
P
Pauli 已提交
257 258 259 260 261 262 263 264 265
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
                                             (unsigned char *)insecret,
                                             insecretlen);
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
                                             (unsigned char *)prevsecret,
                                             prevsecretlen);
    *p++ = OSSL_PARAM_construct_end();

    ret = EVP_KDF_CTX_set_params(kctx, params) <= 0
266
        || EVP_KDF_derive(kctx, outsecret, mdlen) <= 0;
267

268 269 270 271
    if (ret != 0)
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_GENERATE_SECRET,
                 ERR_R_INTERNAL_ERROR);

272
    EVP_KDF_CTX_free(kctx);
273 274
    if (prevsecret == preextractsec)
        OPENSSL_cleanse(preextractsec, mdlen);
275 276 277 278 279 280
    return ret == 0;
}

/*
 * Given an input secret |insecret| of length |insecretlen| generate the
 * handshake secret. This requires the early secret to already have been
281
 * generated. Returns 1 on success  0 on failure.
282 283 284 285
 */
int tls13_generate_handshake_secret(SSL *s, const unsigned char *insecret,
                                size_t insecretlen)
{
286
    /* Calls SSLfatal() if required */
287 288
    return tls13_generate_secret(s, ssl_handshake_md(s), s->early_secret,
                                 insecret, insecretlen,
289 290 291 292 293
                                 (unsigned char *)&s->handshake_secret);
}

/*
 * Given the handshake secret |prev| of length |prevlen| generate the master
294 295
 * secret and store its length in |*secret_size|. Returns 1 on success  0 on
 * failure.
296 297 298 299 300
 */
int tls13_generate_master_secret(SSL *s, unsigned char *out,
                                 unsigned char *prev, size_t prevlen,
                                 size_t *secret_size)
{
301 302 303
    const EVP_MD *md = ssl_handshake_md(s);

    *secret_size = EVP_MD_size(md);
304
    /* Calls SSLfatal() if required */
305
    return tls13_generate_secret(s, md, prev, NULL, 0, out);
306 307
}

308
/*
309 310
 * Generates the mac for the Finished message. Returns the length of the MAC or
 * 0 on error.
311 312 313 314
 */
size_t tls13_final_finish_mac(SSL *s, const char *str, size_t slen,
                             unsigned char *out)
{
315 316
    const char *mdname = EVP_MD_name(ssl_handshake_md(s));
    EVP_MAC *hmac = EVP_MAC_fetch(s->ctx->libctx, "HMAC", s->ctx->propq);
M
Matt Caswell 已提交
317
    unsigned char hash[EVP_MAX_MD_SIZE];
318
    unsigned char finsecret[EVP_MAX_MD_SIZE];
M
Matt Caswell 已提交
319
    size_t hashlen, ret = 0;
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335
    EVP_MAC_CTX *ctx = NULL;
    OSSL_PARAM params[4], *p = params;

    if (hmac == NULL) {
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_FINAL_FINISH_MAC,
                 ERR_R_INTERNAL_ERROR);
        goto err;
    }

    /* Safe to cast away const here since we're not "getting" any data */
    *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_DIGEST,
                                            (char *)mdname, 0);
    if (s->ctx->propq != NULL)
        *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_PROPERTIES,
                                                (char *)s->ctx->propq,
                                                0);
336

337 338
    if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
        /* SSLfatal() already called */
M
Matt Caswell 已提交
339
        goto err;
340
    }
M
Matt Caswell 已提交
341

342
    if (str == s->method->ssl3_enc->server_finished_label) {
343 344 345
        *p++ = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
                                                 s->server_finished_secret,
                                                 hashlen);
346
    } else if (SSL_IS_FIRST_HANDSHAKE(s)) {
347 348 349
        *p++ = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY,
                                                 s->client_finished_secret,
                                                 hashlen);
350 351 352 353 354 355
    } else {
        if (!tls13_derive_finishedkey(s, ssl_handshake_md(s),
                                      s->client_app_traffic_secret,
                                      finsecret, hashlen))
            goto err;

356 357
        *p++ = OSSL_PARAM_construct_octet_string(OSSL_MAC_PARAM_KEY, finsecret,
                                                 hashlen);
358
    }
359
    *p++ = OSSL_PARAM_construct_end();
M
Matt Caswell 已提交
360

361 362 363 364 365 366 367
    ctx = EVP_MAC_CTX_new(hmac);
    if (ctx == NULL
            || !EVP_MAC_CTX_set_params(ctx, params)
            || !EVP_MAC_init(ctx)
            || !EVP_MAC_update(ctx, hash, hashlen)
               /* outsize as per sizeof(peer_finish_md) */
            || !EVP_MAC_final(ctx, out, &hashlen, EVP_MAX_MD_SIZE * 2)) {
368 369
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_FINAL_FINISH_MAC,
                 ERR_R_INTERNAL_ERROR);
M
Matt Caswell 已提交
370
        goto err;
371
    }
372

M
Matt Caswell 已提交
373 374
    ret = hashlen;
 err:
375 376 377
    OPENSSL_cleanse(finsecret, sizeof(finsecret));
    EVP_MAC_CTX_free(ctx);
    EVP_MAC_free(hmac);
M
Matt Caswell 已提交
378
    return ret;
379 380 381 382
}

/*
 * There isn't really a key block in TLSv1.3, but we still need this function
383
 * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
384 385 386 387 388 389
 */
int tls13_setup_key_block(SSL *s)
{
    const EVP_CIPHER *c;
    const EVP_MD *hash;

390
    s->session->cipher = s->s3.tmp.new_cipher;
391 392
    if (!ssl_cipher_get_evp(s->ctx, s->session, &c, &hash, NULL, NULL, NULL,
                            0)) {
393 394
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS13_SETUP_KEY_BLOCK,
                 SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
395 396 397
        return 0;
    }

398
    ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
399
    s->s3.tmp.new_sym_enc = c;
400
    ssl_evp_md_free(s->s3.tmp.new_hash);
401
    s->s3.tmp.new_hash = hash;
402 403 404 405

    return 1;
}

T
Todd Short 已提交
406
static int derive_secret_key_and_iv(SSL *s, int sending, const EVP_MD *md,
407
                                    const EVP_CIPHER *ciph,
408 409 410 411 412 413 414 415
                                    const unsigned char *insecret,
                                    const unsigned char *hash,
                                    const unsigned char *label,
                                    size_t labellen, unsigned char *secret,
                                    unsigned char *iv, EVP_CIPHER_CTX *ciph_ctx)
{
    unsigned char key[EVP_MAX_KEY_LENGTH];
    size_t ivlen, keylen, taglen;
M
Matt Caswell 已提交
416 417 418 419 420 421 422 423 424 425
    int hashleni = EVP_MD_size(md);
    size_t hashlen;

    /* Ensure cast to size_t is safe */
    if (!ossl_assert(hashleni >= 0)) {
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DERIVE_SECRET_KEY_AND_IV,
                 ERR_R_EVP_LIB);
        goto err;
    }
    hashlen = (size_t)hashleni;
426

427
    if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, hashlen,
428
                           secret, hashlen, 1)) {
429
        /* SSLfatal() already called */
430 431 432 433 434 435
        goto err;
    }

    /* TODO(size_t): convert me */
    keylen = EVP_CIPHER_key_length(ciph);
    if (EVP_CIPHER_mode(ciph) == EVP_CIPH_CCM_MODE) {
436 437
        uint32_t algenc;

438
        ivlen = EVP_CCM_TLS_IV_LEN;
439 440 441
        if (s->s3.tmp.new_cipher != NULL) {
            algenc = s->s3.tmp.new_cipher->algorithm_enc;
        } else if (s->session->cipher != NULL) {
442 443
            /* We've not selected a cipher yet - we must be doing early data */
            algenc = s->session->cipher->algorithm_enc;
444 445 446
        } else if (s->psksession != NULL && s->psksession->cipher != NULL) {
            /* We must be doing early data with out-of-band PSK */
            algenc = s->psksession->cipher->algorithm_enc;
447
        } else {
448 449 450
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DERIVE_SECRET_KEY_AND_IV,
                     ERR_R_EVP_LIB);
            goto err;
451 452
        }
        if (algenc & (SSL_AES128CCM8 | SSL_AES256CCM8))
453 454 455 456 457 458 459 460
            taglen = EVP_CCM8_TLS_TAG_LEN;
         else
            taglen = EVP_CCM_TLS_TAG_LEN;
    } else {
        ivlen = EVP_CIPHER_iv_length(ciph);
        taglen = 0;
    }

461 462
    if (!tls13_derive_key(s, md, secret, key, keylen)
            || !tls13_derive_iv(s, md, secret, iv, ivlen)) {
463
        /* SSLfatal() already called */
464 465 466
        goto err;
    }

T
Todd Short 已提交
467
    if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, sending) <= 0
468 469 470 471
        || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)
        || (taglen != 0 && !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
                                                taglen, NULL))
        || EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, -1) <= 0) {
472 473
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_DERIVE_SECRET_KEY_AND_IV,
                 ERR_R_EVP_LIB);
474 475 476 477 478 479 480 481 482
        goto err;
    }

    return 1;
 err:
    OPENSSL_cleanse(key, sizeof(key));
    return 0;
}

483 484
int tls13_change_cipher_state(SSL *s, int which)
{
O
opensslonzos-github 已提交
485 486 487 488 489 490 491 492 493 494
#ifdef CHARSET_EBCDIC
  static const unsigned char client_early_traffic[]       = {0x63, 0x20, 0x65, 0x20,       /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
  static const unsigned char client_handshake_traffic[]   = {0x63, 0x20, 0x68, 0x73, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
  static const unsigned char client_application_traffic[] = {0x63, 0x20, 0x61, 0x70, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
  static const unsigned char server_handshake_traffic[]   = {0x73, 0x20, 0x68, 0x73, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
  static const unsigned char server_application_traffic[] = {0x73, 0x20, 0x61, 0x70, 0x20, /*traffic*/0x74, 0x72, 0x61, 0x66, 0x66, 0x69, 0x63, 0x00};
  static const unsigned char exporter_master_secret[] = {0x65, 0x78, 0x70, 0x20,                    /* master*/  0x6D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x00};
  static const unsigned char resumption_master_secret[] = {0x72, 0x65, 0x73, 0x20,                  /* master*/  0x6D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x00};
  static const unsigned char early_exporter_master_secret[] = {0x65, 0x20, 0x65, 0x78, 0x70, 0x20,  /* master*/  0x6D, 0x61, 0x73, 0x74, 0x65, 0x72, 0x00};
#else
495 496 497 498 499
    static const unsigned char client_early_traffic[] = "c e traffic";
    static const unsigned char client_handshake_traffic[] = "c hs traffic";
    static const unsigned char client_application_traffic[] = "c ap traffic";
    static const unsigned char server_handshake_traffic[] = "s hs traffic";
    static const unsigned char server_application_traffic[] = "s ap traffic";
500
    static const unsigned char exporter_master_secret[] = "exp master";
501
    static const unsigned char resumption_master_secret[] = "res master";
502
    static const unsigned char early_exporter_master_secret[] = "e exp master";
O
opensslonzos-github 已提交
503
#endif
M
Matt Caswell 已提交
504
    unsigned char *iv;
505
    unsigned char secret[EVP_MAX_MD_SIZE];
506 507
    unsigned char hashval[EVP_MAX_MD_SIZE];
    unsigned char *hash = hashval;
508
    unsigned char *insecret;
M
Matt Caswell 已提交
509
    unsigned char *finsecret = NULL;
510
    const char *log_label = NULL;
511
    EVP_CIPHER_CTX *ciph_ctx;
512
    size_t finsecretlen = 0;
513
    const unsigned char *label;
514
    size_t labellen, hashlen = 0;
515
    int ret = 0;
M
Matt Caswell 已提交
516 517
    const EVP_MD *md = NULL;
    const EVP_CIPHER *cipher = NULL;
518 519 520 521 522 523 524

    if (which & SSL3_CC_READ) {
        if (s->enc_read_ctx != NULL) {
            EVP_CIPHER_CTX_reset(s->enc_read_ctx);
        } else {
            s->enc_read_ctx = EVP_CIPHER_CTX_new();
            if (s->enc_read_ctx == NULL) {
525 526
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
527 528 529 530
                goto err;
            }
        }
        ciph_ctx = s->enc_read_ctx;
M
Matt Caswell 已提交
531
        iv = s->read_iv;
532 533 534

        RECORD_LAYER_reset_read_sequence(&s->rlayer);
    } else {
535
        s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
536 537 538 539 540
        if (s->enc_write_ctx != NULL) {
            EVP_CIPHER_CTX_reset(s->enc_write_ctx);
        } else {
            s->enc_write_ctx = EVP_CIPHER_CTX_new();
            if (s->enc_write_ctx == NULL) {
541 542
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
543 544 545 546
                goto err;
            }
        }
        ciph_ctx = s->enc_write_ctx;
M
Matt Caswell 已提交
547
        iv = s->write_iv;
548 549 550 551 552 553

        RECORD_LAYER_reset_write_sequence(&s->rlayer);
    }

    if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
            || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
554 555 556 557 558 559 560 561 562 563 564 565
        if (which & SSL3_CC_EARLY) {
            EVP_MD_CTX *mdctx = NULL;
            long handlen;
            void *hdata;
            unsigned int hashlenui;
            const SSL_CIPHER *sslcipher = SSL_SESSION_get0_cipher(s->session);

            insecret = s->early_secret;
            label = client_early_traffic;
            labellen = sizeof(client_early_traffic) - 1;
            log_label = CLIENT_EARLY_LABEL;

566
            handlen = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
567
            if (handlen <= 0) {
568 569 570
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE,
                         SSL_R_BAD_HANDSHAKE_LENGTH);
571 572
                goto err;
            }
573

574 575 576 577 578 579 580 581 582 583 584
            if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
                    && s->max_early_data > 0
                    && s->session->ext.max_early_data == 0) {
                /*
                 * If we are attempting to send early data, and we've decided to
                 * actually do it but max_early_data in s->session is 0 then we
                 * must be using an external PSK.
                 */
                if (!ossl_assert(s->psksession != NULL
                        && s->max_early_data ==
                           s->psksession->ext.max_early_data)) {
585 586 587
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                             SSL_F_TLS13_CHANGE_CIPHER_STATE,
                             ERR_R_INTERNAL_ERROR);
588 589
                    goto err;
                }
590
                sslcipher = SSL_SESSION_get0_cipher(s->psksession);
591
            }
592
            if (sslcipher == NULL) {
593 594
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE, SSL_R_BAD_PSK);
595 596 597 598 599 600 601 602 603 604
                goto err;
            }

            /*
             * We need to calculate the handshake digest using the digest from
             * the session. We haven't yet selected our ciphersuite so we can't
             * use ssl_handshake_md().
             */
            mdctx = EVP_MD_CTX_new();
            if (mdctx == NULL) {
605 606
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
607 608
                goto err;
            }
609 610 611 612 613 614 615 616 617

            /*
             * This ups the ref count on cipher so we better make sure we free
             * it again
             */
            if (!ssl_cipher_get_evp_cipher(s->ctx, sslcipher, &cipher)) {
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE,
                         SSL_R_ALGORITHM_FETCH_FAILED);
P
Pauli 已提交
618
                EVP_MD_CTX_free(mdctx);
619 620 621
                goto err;
            }

622
            md = ssl_md(s->ctx, sslcipher->algorithm2);
623 624 625
            if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
                    || !EVP_DigestUpdate(mdctx, hdata, handlen)
                    || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
626 627
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
628 629 630 631 632
                EVP_MD_CTX_free(mdctx);
                goto err;
            }
            hashlen = hashlenui;
            EVP_MD_CTX_free(mdctx);
633 634 635 636 637

            if (!tls13_hkdf_expand(s, md, insecret,
                                   early_exporter_master_secret,
                                   sizeof(early_exporter_master_secret) - 1,
                                   hashval, hashlen,
638 639
                                   s->early_exporter_master_secret, hashlen,
                                   1)) {
640 641 642 643
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
                         SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
                goto err;
            }
644 645 646 647 648 649

            if (!ssl_log_secret(s, EARLY_EXPORTER_SECRET_LABEL,
                                s->early_exporter_master_secret, hashlen)) {
                /* SSLfatal() already called */
                goto err;
            }
650
        } else if (which & SSL3_CC_HANDSHAKE) {
651
            insecret = s->handshake_secret;
M
Matt Caswell 已提交
652
            finsecret = s->client_finished_secret;
653
            finsecretlen = EVP_MD_size(ssl_handshake_md(s));
654 655
            label = client_handshake_traffic;
            labellen = sizeof(client_handshake_traffic) - 1;
656
            log_label = CLIENT_HANDSHAKE_LABEL;
657
            /*
F
FdaSilvaYY 已提交
658
             * The handshake hash used for the server read/client write handshake
659 660 661 662 663 664
             * traffic secret is the same as the hash for the server
             * write/client read handshake traffic secret. However, if we
             * processed early data then we delay changing the server
             * read/client write cipher state until later, and the handshake
             * hashes have moved on. Therefore we use the value saved earlier
             * when we did the server write/client read change cipher state.
665
             */
666
            hash = s->handshake_traffic_hash;
667
        } else {
668
            insecret = s->master_secret;
669 670
            label = client_application_traffic;
            labellen = sizeof(client_application_traffic) - 1;
671
            log_label = CLIENT_APPLICATION_LABEL;
672 673 674 675 676 677 678
            /*
             * For this we only use the handshake hashes up until the server
             * Finished hash. We do not include the client's Finished, which is
             * what ssl_handshake_hash() would give us. Instead we use the
             * previously saved value.
             */
            hash = s->server_finished_hash;
679 680
        }
    } else {
681
        /* Early data never applies to client-read/server-write */
682 683
        if (which & SSL3_CC_HANDSHAKE) {
            insecret = s->handshake_secret;
M
Matt Caswell 已提交
684
            finsecret = s->server_finished_secret;
685
            finsecretlen = EVP_MD_size(ssl_handshake_md(s));
686 687
            label = server_handshake_traffic;
            labellen = sizeof(server_handshake_traffic) - 1;
688
            log_label = SERVER_HANDSHAKE_LABEL;
689
        } else {
690
            insecret = s->master_secret;
691 692
            label = server_application_traffic;
            labellen = sizeof(server_application_traffic) - 1;
693
            log_label = SERVER_APPLICATION_LABEL;
694 695 696
        }
    }

697 698
    if (!(which & SSL3_CC_EARLY)) {
        md = ssl_handshake_md(s);
699
        cipher = s->s3.tmp.new_sym_enc;
700 701
        if (!ssl3_digest_cached_records(s, 1)
                || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
702
            /* SSLfatal() already called */;
703 704
            goto err;
        }
705 706
    }

707 708 709 710 711 712 713
    /*
     * Save the hash of handshakes up to now for use when we calculate the
     * client application traffic secret
     */
    if (label == server_application_traffic)
        memcpy(s->server_finished_hash, hashval, hashlen);

714
    if (label == server_handshake_traffic)
715 716
        memcpy(s->handshake_traffic_hash, hashval, hashlen);

717 718 719 720 721 722 723 724
    if (label == client_application_traffic) {
        /*
         * We also create the resumption master secret, but this time use the
         * hash for the whole handshake including the Client Finished
         */
        if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
                               resumption_master_secret,
                               sizeof(resumption_master_secret) - 1,
M
Matt Caswell 已提交
725
                               hashval, hashlen, s->resumption_master_secret,
726
                               hashlen, 1)) {
727
            /* SSLfatal() already called */
728 729 730 731
            goto err;
        }
    }

732 733 734
    if (!derive_secret_key_and_iv(s, which & SSL3_CC_WRITE, md, cipher,
                                  insecret, hash, label, labellen, secret, iv,
                                  ciph_ctx)) {
735
        /* SSLfatal() already called */
736
        goto err;
737
    }
738

739
    if (label == server_application_traffic) {
740
        memcpy(s->server_app_traffic_secret, secret, hashlen);
741 742 743 744 745
        /* Now we create the exporter master secret */
        if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
                               exporter_master_secret,
                               sizeof(exporter_master_secret) - 1,
                               hash, hashlen, s->exporter_master_secret,
746
                               hashlen, 1)) {
747 748 749
            /* SSLfatal() already called */
            goto err;
        }
750 751 752 753 754 755

        if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
                            hashlen)) {
            /* SSLfatal() already called */
            goto err;
        }
756
    } else if (label == client_application_traffic)
757 758
        memcpy(s->client_app_traffic_secret, secret, hashlen);

759
    if (!ssl_log_secret(s, log_label, secret, hashlen)) {
760
        /* SSLfatal() already called */
761 762 763
        goto err;
    }

764 765 766
    if (finsecret != NULL
            && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
                                         finsecret, finsecretlen)) {
767
        /* SSLfatal() already called */
768 769 770
        goto err;
    }

771 772 773 774
    if (!s->server && label == client_early_traffic)
        s->statem.enc_write_state = ENC_WRITE_STATE_WRITE_PLAIN_ALERTS;
    else
        s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
775 776
    ret = 1;
 err:
777 778 779 780
    if ((which & SSL3_CC_EARLY) != 0) {
        /* We up-refed this so now we need to down ref */
        ssl_evp_cipher_free(cipher);
    }
781 782 783
    OPENSSL_cleanse(secret, sizeof(secret));
    return ret;
}
784

T
Todd Short 已提交
785
int tls13_update_key(SSL *s, int sending)
786
{
O
opensslonzos-github 已提交
787 788 789 790 791
#ifdef CHARSET_EBCDIC
  static const unsigned char application_traffic[] = { 0x74, 0x72 ,0x61 ,0x66 ,0x66 ,0x69 ,0x63 ,0x20 ,0x75 ,0x70 ,0x64, 0x00};
#else
  static const unsigned char application_traffic[] = "traffic upd";
#endif
792 793 794 795 796 797
    const EVP_MD *md = ssl_handshake_md(s);
    size_t hashlen = EVP_MD_size(md);
    unsigned char *insecret, *iv;
    unsigned char secret[EVP_MAX_MD_SIZE];
    EVP_CIPHER_CTX *ciph_ctx;
    int ret = 0;
798

T
Todd Short 已提交
799
    if (s->server == sending)
800 801 802
        insecret = s->server_app_traffic_secret;
    else
        insecret = s->client_app_traffic_secret;
M
Matt Caswell 已提交
803

T
Todd Short 已提交
804
    if (sending) {
805
        s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
806 807 808 809 810 811 812
        iv = s->write_iv;
        ciph_ctx = s->enc_write_ctx;
        RECORD_LAYER_reset_write_sequence(&s->rlayer);
    } else {
        iv = s->read_iv;
        ciph_ctx = s->enc_read_ctx;
        RECORD_LAYER_reset_read_sequence(&s->rlayer);
813
    }
814

T
Todd Short 已提交
815
    if (!derive_secret_key_and_iv(s, sending, ssl_handshake_md(s),
816
                                  s->s3.tmp.new_sym_enc, insecret, NULL,
817
                                  application_traffic,
818
                                  sizeof(application_traffic) - 1, secret, iv,
819 820
                                  ciph_ctx)) {
        /* SSLfatal() already called */
821
        goto err;
822
    }
823 824

    memcpy(insecret, secret, hashlen);
825

826
    s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
827
    ret = 1;
828 829
 err:
    OPENSSL_cleanse(secret, sizeof(secret));
830
    return ret;
831
}
832 833 834

int tls13_alert_code(int code)
{
M
Matt Caswell 已提交
835 836
    /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
    if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
837 838 839 840
        return code;

    return tls1_alert_code(code);
}
841 842 843 844 845 846 847

int tls13_export_keying_material(SSL *s, unsigned char *out, size_t olen,
                                 const char *label, size_t llen,
                                 const unsigned char *context,
                                 size_t contextlen, int use_context)
{
    unsigned char exportsecret[EVP_MAX_MD_SIZE];
O
opensslonzos-github 已提交
848 849 850
#ifdef CHARSET_EBCDIC
    static const unsigned char exporterlabel[] = {0x65, 0x78, 0x70, 0x6F, 0x72, 0x74, 0x65, 0x72, 0x00};
#else
851
    static const unsigned char exporterlabel[] = "exporter";
O
opensslonzos-github 已提交
852
#endif
853
    unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
854 855
    const EVP_MD *md = ssl_handshake_md(s);
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
856
    unsigned int hashsize, datalen;
857 858
    int ret = 0;

859
    if (ctx == NULL || !ossl_statem_export_allowed(s))
860 861 862 863 864 865 866 867
        goto err;

    if (!use_context)
        contextlen = 0;

    if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
            || EVP_DigestUpdate(ctx, context, contextlen) <= 0
            || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
868 869
            || EVP_DigestInit_ex(ctx, md, NULL) <= 0
            || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
870
            || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
871
                                  (const unsigned char *)label, llen,
872
                                  data, datalen, exportsecret, hashsize, 0)
873
            || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
874
                                  sizeof(exporterlabel) - 1, hash, hashsize,
875
                                  out, olen, 0))
876 877 878 879 880 881 882
        goto err;

    ret = 1;
 err:
    EVP_MD_CTX_free(ctx);
    return ret;
}
883 884 885 886 887 888

int tls13_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
                                       const char *label, size_t llen,
                                       const unsigned char *context,
                                       size_t contextlen)
{
O
opensslonzos-github 已提交
889 890 891 892 893
#ifdef CHARSET_EBCDIC
  static const unsigned char exporterlabel[] = {0x65, 0x78, 0x70, 0x6F, 0x72, 0x74, 0x65, 0x72, 0x00};
#else
  static const unsigned char exporterlabel[] = "exporter";
#endif
894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910
    unsigned char exportsecret[EVP_MAX_MD_SIZE];
    unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
    const EVP_MD *md;
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
    unsigned int hashsize, datalen;
    int ret = 0;
    const SSL_CIPHER *sslcipher;

    if (ctx == NULL || !ossl_statem_export_early_allowed(s))
        goto err;

    if (!s->server && s->max_early_data > 0
            && s->session->ext.max_early_data == 0)
        sslcipher = SSL_SESSION_get0_cipher(s->psksession);
    else
        sslcipher = SSL_SESSION_get0_cipher(s->session);

911
    md = ssl_md(s->ctx, sslcipher->algorithm2);
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934

    /*
     * Calculate the hash value and store it in |data|. The reason why
     * the empty string is used is that the definition of TLS-Exporter
     * is like so:
     *
     * TLS-Exporter(label, context_value, key_length) =
     *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
     *                       "exporter", Hash(context_value), key_length)
     *
     * Derive-Secret(Secret, Label, Messages) =
     *       HKDF-Expand-Label(Secret, Label,
     *                         Transcript-Hash(Messages), Hash.length)
     *
     * Here Transcript-Hash is the cipher suite hash algorithm.
     */
    if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
            || EVP_DigestUpdate(ctx, context, contextlen) <= 0
            || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
            || EVP_DigestInit_ex(ctx, md, NULL) <= 0
            || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
            || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
                                  (const unsigned char *)label, llen,
935
                                  data, datalen, exportsecret, hashsize, 0)
936 937
            || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
                                  sizeof(exporterlabel) - 1, hash, hashsize,
938
                                  out, olen, 0))
939 940 941 942 943 944 945
        goto err;

    ret = 1;
 err:
    EVP_MD_CTX_free(ctx);
    return ret;
}