Coverage Report

Created: 2025-06-13 06:58

/src/openssl31/ssl/tls13_enc.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2016-2022 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include <stdlib.h>
11
#include "ssl_local.h"
12
#include "internal/ktls.h"
13
#include "record/record_local.h"
14
#include "internal/cryptlib.h"
15
#include <openssl/evp.h>
16
#include <openssl/kdf.h>
17
#include <openssl/core_names.h>
18
19
11.5k
#define TLS13_MAX_LABEL_LEN     249
20
21
/* ASCII: "tls13 ", in hex for EBCDIC compatibility */
22
static const unsigned char label_prefix[] = "\x74\x6C\x73\x31\x33\x20";
23
24
/*
25
 * Given a |secret|; a |label| of length |labellen|; and |data| of length
26
 * |datalen| (e.g. typically a hash of the handshake messages), derive a new
27
 * secret |outlen| bytes long and store it in the location pointed to be |out|.
28
 * The |data| value may be zero length. Any errors will be treated as fatal if
29
 * |fatal| is set. Returns 1 on success  0 on failure.
30
 */
31
int tls13_hkdf_expand(SSL *s, const EVP_MD *md, const unsigned char *secret,
32
                      const unsigned char *label, size_t labellen,
33
                      const unsigned char *data, size_t datalen,
34
                      unsigned char *out, size_t outlen, int fatal)
35
11.5k
{
36
11.5k
    EVP_KDF *kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_TLS1_3_KDF,
37
11.5k
                                 s->ctx->propq);
38
11.5k
    EVP_KDF_CTX *kctx;
39
11.5k
    OSSL_PARAM params[7], *p = params;
40
11.5k
    int mode = EVP_PKEY_HKDEF_MODE_EXPAND_ONLY;
41
11.5k
    const char *mdname = EVP_MD_get0_name(md);
42
11.5k
    int ret;
43
11.5k
    size_t hashlen;
44
45
11.5k
    kctx = EVP_KDF_CTX_new(kdf);
46
11.5k
    EVP_KDF_free(kdf);
47
11.5k
    if (kctx == NULL)
48
0
        return 0;
49
50
11.5k
    if (labellen > TLS13_MAX_LABEL_LEN) {
51
0
        if (fatal) {
52
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
53
0
        } else {
54
            /*
55
             * Probably we have been called from SSL_export_keying_material(),
56
             * or SSL_export_keying_material_early().
57
             */
58
0
            ERR_raise(ERR_LIB_SSL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
59
0
        }
60
0
        EVP_KDF_CTX_free(kctx);
61
0
        return 0;
62
0
    }
63
64
11.5k
    if ((ret = EVP_MD_get_size(md)) <= 0) {
65
0
        EVP_KDF_CTX_free(kctx);
66
0
        if (fatal)
67
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
68
0
        else
69
0
            ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
70
0
        return 0;
71
0
    }
72
11.5k
    hashlen = (size_t)ret;
73
74
11.5k
    *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
75
11.5k
    *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
76
11.5k
                                            (char *)mdname, 0);
77
11.5k
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
78
11.5k
                                             (unsigned char *)secret, hashlen);
79
11.5k
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
80
11.5k
                                             (unsigned char *)label_prefix,
81
11.5k
                                             sizeof(label_prefix) - 1);
82
11.5k
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
83
11.5k
                                             (unsigned char *)label, labellen);
84
11.5k
    if (data != NULL)
85
3.80k
        *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_DATA,
86
3.80k
                                                 (unsigned char *)data,
87
3.80k
                                                 datalen);
88
11.5k
    *p++ = OSSL_PARAM_construct_end();
89
90
11.5k
    ret = EVP_KDF_derive(kctx, out, outlen, params) <= 0;
91
11.5k
    EVP_KDF_CTX_free(kctx);
92
93
11.5k
    if (ret != 0) {
94
0
        if (fatal)
95
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
96
0
        else
97
0
            ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
98
0
    }
99
100
11.5k
    return ret == 0;
101
11.5k
}
102
103
/*
104
 * Given a |secret| generate a |key| of length |keylen| bytes. Returns 1 on
105
 * success  0 on failure.
106
 */
107
int tls13_derive_key(SSL *s, const EVP_MD *md, const unsigned char *secret,
108
                     unsigned char *key, size_t keylen)
109
39.6k
{
110
    /* ASCII: "key", in hex for EBCDIC compatibility */
111
39.6k
    static const unsigned char keylabel[] = "\x6B\x65\x79";
112
113
39.6k
    return tls13_hkdf_expand(s, md, secret, keylabel, sizeof(keylabel) - 1,
114
39.6k
                             NULL, 0, key, keylen, 1);
115
39.6k
}
116
117
/*
118
 * Given a |secret| generate an |iv| of length |ivlen| bytes. Returns 1 on
119
 * success  0 on failure.
120
 */
121
int tls13_derive_iv(SSL *s, const EVP_MD *md, const unsigned char *secret,
122
                    unsigned char *iv, size_t ivlen)
123
39.6k
{
124
    /* ASCII: "iv", in hex for EBCDIC compatibility */
125
39.6k
    static const unsigned char ivlabel[] = "\x69\x76";
126
127
39.6k
    return tls13_hkdf_expand(s, md, secret, ivlabel, sizeof(ivlabel) - 1,
128
39.6k
                             NULL, 0, iv, ivlen, 1);
129
39.6k
}
130
131
int tls13_derive_finishedkey(SSL *s, const EVP_MD *md,
132
                             const unsigned char *secret,
133
                             unsigned char *fin, size_t finlen)
134
26.1k
{
135
    /* ASCII: "finished", in hex for EBCDIC compatibility */
136
26.1k
    static const unsigned char finishedlabel[] = "\x66\x69\x6E\x69\x73\x68\x65\x64";
137
138
26.1k
    return tls13_hkdf_expand(s, md, secret, finishedlabel,
139
26.1k
                             sizeof(finishedlabel) - 1, NULL, 0, fin, finlen, 1);
140
26.1k
}
141
142
/*
143
 * Given the previous secret |prevsecret| and a new input secret |insecret| of
144
 * length |insecretlen|, generate a new secret and store it in the location
145
 * pointed to by |outsecret|. Returns 1 on success  0 on failure.
146
 */
147
int tls13_generate_secret(SSL *s, const EVP_MD *md,
148
                          const unsigned char *prevsecret,
149
                          const unsigned char *insecret,
150
                          size_t insecretlen,
151
                          unsigned char *outsecret)
152
18.7k
{
153
18.7k
    size_t mdlen;
154
18.7k
    int mdleni;
155
18.7k
    int ret;
156
18.7k
    EVP_KDF *kdf;
157
18.7k
    EVP_KDF_CTX *kctx;
158
18.7k
    OSSL_PARAM params[7], *p = params;
159
18.7k
    int mode = EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY;
160
18.7k
    const char *mdname = EVP_MD_get0_name(md);
161
    /* ASCII: "derived", in hex for EBCDIC compatibility */
162
18.7k
    static const char derived_secret_label[] = "\x64\x65\x72\x69\x76\x65\x64";
163
164
18.7k
    kdf = EVP_KDF_fetch(s->ctx->libctx, OSSL_KDF_NAME_TLS1_3_KDF, s->ctx->propq);
165
18.7k
    kctx = EVP_KDF_CTX_new(kdf);
166
18.7k
    EVP_KDF_free(kdf);
167
18.7k
    if (kctx == NULL) {
168
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
169
0
        return 0;
170
0
    }
171
172
18.7k
    mdleni = EVP_MD_get_size(md);
173
    /* Ensure cast to size_t is safe */
174
18.7k
    if (!ossl_assert(mdleni >= 0)) {
175
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
176
0
        EVP_KDF_CTX_free(kctx);
177
0
        return 0;
178
0
    }
179
18.7k
    mdlen = (size_t)mdleni;
180
181
18.7k
    *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
182
18.7k
    *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
183
18.7k
                                            (char *)mdname, 0);
184
18.7k
    if (insecret != NULL)
185
7.19k
        *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
186
7.19k
                                                 (unsigned char *)insecret,
187
7.19k
                                                 insecretlen);
188
18.7k
    if (prevsecret != NULL)
189
11.5k
        *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
190
11.5k
                                                 (unsigned char *)prevsecret, mdlen);
191
18.7k
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
192
18.7k
                                             (unsigned char *)label_prefix,
193
18.7k
                                             sizeof(label_prefix) - 1);
194
18.7k
    *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
195
18.7k
                                             (unsigned char *)derived_secret_label,
196
18.7k
                                             sizeof(derived_secret_label) - 1);
197
18.7k
    *p++ = OSSL_PARAM_construct_end();
198
199
18.7k
    ret = EVP_KDF_derive(kctx, outsecret, mdlen, params) <= 0;
200
201
18.7k
    if (ret != 0)
202
18.7k
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
203
204
18.7k
    EVP_KDF_CTX_free(kctx);
205
18.7k
    return ret == 0;
206
18.7k
}
207
208
/*
209
 * Given an input secret |insecret| of length |insecretlen| generate the
210
 * handshake secret. This requires the early secret to already have been
211
 * generated. Returns 1 on success  0 on failure.
212
 */
213
int tls13_generate_handshake_secret(SSL *s, const unsigned char *insecret,
214
                                size_t insecretlen)
215
13.2k
{
216
    /* Calls SSLfatal() if required */
217
13.2k
    return tls13_generate_secret(s, ssl_handshake_md(s), s->early_secret,
218
13.2k
                                 insecret, insecretlen,
219
13.2k
                                 (unsigned char *)&s->handshake_secret);
220
13.2k
}
221
222
/*
223
 * Given the handshake secret |prev| of length |prevlen| generate the master
224
 * secret and store its length in |*secret_size|. Returns 1 on success  0 on
225
 * failure.
226
 */
227
int tls13_generate_master_secret(SSL *s, unsigned char *out,
228
                                 unsigned char *prev, size_t prevlen,
229
                                 size_t *secret_size)
230
4.35k
{
231
4.35k
    const EVP_MD *md = ssl_handshake_md(s);
232
233
4.35k
    *secret_size = EVP_MD_get_size(md);
234
    /* Calls SSLfatal() if required */
235
4.35k
    return tls13_generate_secret(s, md, prev, NULL, 0, out);
236
4.35k
}
237
238
/*
239
 * Generates the mac for the Finished message. Returns the length of the MAC or
240
 * 0 on error.
241
 */
242
size_t tls13_final_finish_mac(SSL *s, const char *str, size_t slen,
243
                             unsigned char *out)
244
13.5k
{
245
13.5k
    const EVP_MD *md = ssl_handshake_md(s);
246
13.5k
    const char *mdname = EVP_MD_get0_name(md);
247
13.5k
    unsigned char hash[EVP_MAX_MD_SIZE];
248
13.5k
    unsigned char finsecret[EVP_MAX_MD_SIZE];
249
13.5k
    unsigned char *key = NULL;
250
13.5k
    size_t len = 0, hashlen;
251
13.5k
    OSSL_PARAM params[2], *p = params;
252
253
13.5k
    if (md == NULL)
254
0
        return 0;
255
256
    /* Safe to cast away const here since we're not "getting" any data */
257
13.5k
    if (s->ctx->propq != NULL)
258
0
        *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_PROPERTIES,
259
0
                                                (char *)s->ctx->propq,
260
0
                                                0);
261
13.5k
    *p = OSSL_PARAM_construct_end();
262
263
13.5k
    if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
264
        /* SSLfatal() already called */
265
0
        goto err;
266
0
    }
267
268
13.5k
    if (str == s->method->ssl3_enc->server_finished_label) {
269
7.76k
        key = s->server_finished_secret;
270
7.76k
    } else if (SSL_IS_FIRST_HANDSHAKE(s)) {
271
5.77k
        key = s->client_finished_secret;
272
5.77k
    } else {
273
0
        if (!tls13_derive_finishedkey(s, md,
274
0
                                      s->client_app_traffic_secret,
275
0
                                      finsecret, hashlen))
276
0
            goto err;
277
0
        key = finsecret;
278
0
    }
279
280
13.5k
    if (!EVP_Q_mac(s->ctx->libctx, "HMAC", s->ctx->propq, mdname,
281
13.5k
                   params, key, hashlen, hash, hashlen,
282
                   /* outsize as per sizeof(peer_finish_md) */
283
13.5k
                   out, EVP_MAX_MD_SIZE * 2, &len)) {
284
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
285
0
        goto err;
286
0
    }
287
288
13.5k
 err:
289
13.5k
    OPENSSL_cleanse(finsecret, sizeof(finsecret));
290
13.5k
    return len;
291
13.5k
}
292
293
/*
294
 * There isn't really a key block in TLSv1.3, but we still need this function
295
 * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
296
 */
297
int tls13_setup_key_block(SSL *s)
298
13.2k
{
299
13.2k
    const EVP_CIPHER *c;
300
13.2k
    const EVP_MD *hash;
301
302
13.2k
    s->session->cipher = s->s3.tmp.new_cipher;
303
13.2k
    if (!ssl_cipher_get_evp(s->ctx, s->session, &c, &hash, NULL, NULL, NULL,
304
13.2k
                            0)) {
305
        /* Error is already recorded */
306
0
        SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
307
0
        return 0;
308
0
    }
309
310
13.2k
    ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
311
13.2k
    s->s3.tmp.new_sym_enc = c;
312
13.2k
    ssl_evp_md_free(s->s3.tmp.new_hash);
313
13.2k
    s->s3.tmp.new_hash = hash;
314
315
13.2k
    return 1;
316
13.2k
}
317
318
static int derive_secret_key_and_iv(SSL *s, int sending, const EVP_MD *md,
319
                                    const EVP_CIPHER *ciph,
320
                                    const unsigned char *insecret,
321
                                    const unsigned char *hash,
322
                                    const unsigned char *label,
323
                                    size_t labellen, unsigned char *secret,
324
                                    unsigned char *key, unsigned char *iv,
325
                                    EVP_CIPHER_CTX *ciph_ctx)
326
2.88k
{
327
2.88k
    size_t ivlen, keylen, taglen;
328
2.88k
    int hashleni = EVP_MD_get_size(md);
329
2.88k
    size_t hashlen;
330
331
    /* Ensure cast to size_t is safe */
332
2.88k
    if (!ossl_assert(hashleni >= 0)) {
333
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
334
0
        return 0;
335
0
    }
336
2.88k
    hashlen = (size_t)hashleni;
337
338
2.88k
    if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, hashlen,
339
2.88k
                           secret, hashlen, 1)) {
340
        /* SSLfatal() already called */
341
0
        return 0;
342
0
    }
343
344
2.88k
    keylen = EVP_CIPHER_get_key_length(ciph);
345
2.88k
    if (EVP_CIPHER_get_mode(ciph) == EVP_CIPH_CCM_MODE) {
346
0
        uint32_t algenc;
347
348
0
        ivlen = EVP_CCM_TLS_IV_LEN;
349
0
        if (s->s3.tmp.new_cipher != NULL) {
350
0
            algenc = s->s3.tmp.new_cipher->algorithm_enc;
351
0
        } else if (s->session->cipher != NULL) {
352
            /* We've not selected a cipher yet - we must be doing early data */
353
0
            algenc = s->session->cipher->algorithm_enc;
354
0
        } else if (s->psksession != NULL && s->psksession->cipher != NULL) {
355
            /* We must be doing early data with out-of-band PSK */
356
0
            algenc = s->psksession->cipher->algorithm_enc;
357
0
        } else {
358
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
359
0
            return 0;
360
0
        }
361
0
        if (algenc & (SSL_AES128CCM8 | SSL_AES256CCM8))
362
0
            taglen = EVP_CCM8_TLS_TAG_LEN;
363
0
         else
364
0
            taglen = EVP_CCM_TLS_TAG_LEN;
365
2.88k
    } else {
366
2.88k
        ivlen = EVP_CIPHER_get_iv_length(ciph);
367
2.88k
        taglen = 0;
368
2.88k
    }
369
370
2.88k
    if (!tls13_derive_key(s, md, secret, key, keylen)
371
2.88k
            || !tls13_derive_iv(s, md, secret, iv, ivlen)) {
372
        /* SSLfatal() already called */
373
0
        return 0;
374
0
    }
375
376
2.88k
    if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, sending) <= 0
377
2.88k
        || EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL) <= 0
378
2.88k
        || (taglen != 0 && EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
379
0
                                                taglen, NULL) <= 0)
380
2.88k
        || EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, -1) <= 0) {
381
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
382
0
        return 0;
383
0
    }
384
385
2.88k
    return 1;
386
2.88k
}
387
388
int tls13_change_cipher_state(SSL *s, int which)
389
2.88k
{
390
    /* ASCII: "c e traffic", in hex for EBCDIC compatibility */
391
2.88k
    static const unsigned char client_early_traffic[] = "\x63\x20\x65\x20\x74\x72\x61\x66\x66\x69\x63";
392
    /* ASCII: "c hs traffic", in hex for EBCDIC compatibility */
393
2.88k
    static const unsigned char client_handshake_traffic[] = "\x63\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
394
    /* ASCII: "c ap traffic", in hex for EBCDIC compatibility */
395
2.88k
    static const unsigned char client_application_traffic[] = "\x63\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
396
    /* ASCII: "s hs traffic", in hex for EBCDIC compatibility */
397
2.88k
    static const unsigned char server_handshake_traffic[] = "\x73\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
398
    /* ASCII: "s ap traffic", in hex for EBCDIC compatibility */
399
2.88k
    static const unsigned char server_application_traffic[] = "\x73\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
400
    /* ASCII: "exp master", in hex for EBCDIC compatibility */
401
2.88k
    static const unsigned char exporter_master_secret[] = "\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
402
    /* ASCII: "res master", in hex for EBCDIC compatibility */
403
2.88k
    static const unsigned char resumption_master_secret[] = "\x72\x65\x73\x20\x6D\x61\x73\x74\x65\x72";
404
    /* ASCII: "e exp master", in hex for EBCDIC compatibility */
405
2.88k
    static const unsigned char early_exporter_master_secret[] = "\x65\x20\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
406
2.88k
    unsigned char *iv;
407
2.88k
    unsigned char key[EVP_MAX_KEY_LENGTH];
408
2.88k
    unsigned char secret[EVP_MAX_MD_SIZE];
409
2.88k
    unsigned char hashval[EVP_MAX_MD_SIZE];
410
2.88k
    unsigned char *hash = hashval;
411
2.88k
    unsigned char *insecret;
412
2.88k
    unsigned char *finsecret = NULL;
413
2.88k
    const char *log_label = NULL;
414
2.88k
    EVP_CIPHER_CTX *ciph_ctx;
415
2.88k
    size_t finsecretlen = 0;
416
2.88k
    const unsigned char *label;
417
2.88k
    size_t labellen, hashlen = 0;
418
2.88k
    int ret = 0;
419
2.88k
    const EVP_MD *md = NULL;
420
2.88k
    const EVP_CIPHER *cipher = NULL;
421
#if !defined(OPENSSL_NO_KTLS) && defined(OPENSSL_KTLS_TLS13)
422
    ktls_crypto_info_t crypto_info;
423
    BIO *bio;
424
#endif
425
426
2.88k
    if (which & SSL3_CC_READ) {
427
1.09k
        if (s->enc_read_ctx != NULL) {
428
0
            EVP_CIPHER_CTX_reset(s->enc_read_ctx);
429
1.09k
        } else {
430
1.09k
            s->enc_read_ctx = EVP_CIPHER_CTX_new();
431
1.09k
            if (s->enc_read_ctx == NULL) {
432
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
433
0
                goto err;
434
0
            }
435
1.09k
        }
436
1.09k
        ciph_ctx = s->enc_read_ctx;
437
1.09k
        iv = s->read_iv;
438
439
1.09k
        RECORD_LAYER_reset_read_sequence(&s->rlayer);
440
1.79k
    } else {
441
1.79k
        s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
442
1.79k
        if (s->enc_write_ctx != NULL) {
443
896
            EVP_CIPHER_CTX_reset(s->enc_write_ctx);
444
896
        } else {
445
896
            s->enc_write_ctx = EVP_CIPHER_CTX_new();
446
896
            if (s->enc_write_ctx == NULL) {
447
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
448
0
                goto err;
449
0
            }
450
896
        }
451
1.79k
        ciph_ctx = s->enc_write_ctx;
452
1.79k
        iv = s->write_iv;
453
454
1.79k
        RECORD_LAYER_reset_write_sequence(&s->rlayer);
455
1.79k
    }
456
457
2.88k
    if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
458
2.88k
            || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
459
896
        if (which & SSL3_CC_EARLY) {
460
0
            EVP_MD_CTX *mdctx = NULL;
461
0
            long handlen;
462
0
            void *hdata;
463
0
            unsigned int hashlenui;
464
0
            const SSL_CIPHER *sslcipher = SSL_SESSION_get0_cipher(s->session);
465
466
0
            insecret = s->early_secret;
467
0
            label = client_early_traffic;
468
0
            labellen = sizeof(client_early_traffic) - 1;
469
0
            log_label = CLIENT_EARLY_LABEL;
470
471
0
            handlen = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
472
0
            if (handlen <= 0) {
473
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
474
0
                goto err;
475
0
            }
476
477
0
            if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
478
0
                    && s->max_early_data > 0
479
0
                    && s->session->ext.max_early_data == 0) {
480
                /*
481
                 * If we are attempting to send early data, and we've decided to
482
                 * actually do it but max_early_data in s->session is 0 then we
483
                 * must be using an external PSK.
484
                 */
485
0
                if (!ossl_assert(s->psksession != NULL
486
0
                        && s->max_early_data ==
487
0
                           s->psksession->ext.max_early_data)) {
488
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
489
0
                    goto err;
490
0
                }
491
0
                sslcipher = SSL_SESSION_get0_cipher(s->psksession);
492
0
            }
493
0
            if (sslcipher == NULL) {
494
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
495
0
                goto err;
496
0
            }
497
498
            /*
499
             * We need to calculate the handshake digest using the digest from
500
             * the session. We haven't yet selected our ciphersuite so we can't
501
             * use ssl_handshake_md().
502
             */
503
0
            mdctx = EVP_MD_CTX_new();
504
0
            if (mdctx == NULL) {
505
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
506
0
                goto err;
507
0
            }
508
509
            /*
510
             * This ups the ref count on cipher so we better make sure we free
511
             * it again
512
             */
513
0
            if (!ssl_cipher_get_evp_cipher(s->ctx, sslcipher, &cipher)) {
514
                /* Error is already recorded */
515
0
                SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
516
0
                EVP_MD_CTX_free(mdctx);
517
0
                goto err;
518
0
            }
519
520
0
            md = ssl_md(s->ctx, sslcipher->algorithm2);
521
0
            if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
522
0
                    || !EVP_DigestUpdate(mdctx, hdata, handlen)
523
0
                    || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
524
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
525
0
                EVP_MD_CTX_free(mdctx);
526
0
                goto err;
527
0
            }
528
0
            hashlen = hashlenui;
529
0
            EVP_MD_CTX_free(mdctx);
530
531
0
            if (!tls13_hkdf_expand(s, md, insecret,
532
0
                                   early_exporter_master_secret,
533
0
                                   sizeof(early_exporter_master_secret) - 1,
534
0
                                   hashval, hashlen,
535
0
                                   s->early_exporter_master_secret, hashlen,
536
0
                                   1)) {
537
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
538
0
                goto err;
539
0
            }
540
541
0
            if (!ssl_log_secret(s, EARLY_EXPORTER_SECRET_LABEL,
542
0
                                s->early_exporter_master_secret, hashlen)) {
543
                /* SSLfatal() already called */
544
0
                goto err;
545
0
            }
546
896
        } else if (which & SSL3_CC_HANDSHAKE) {
547
896
            insecret = s->handshake_secret;
548
896
            finsecret = s->client_finished_secret;
549
896
            finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
550
896
            label = client_handshake_traffic;
551
896
            labellen = sizeof(client_handshake_traffic) - 1;
552
896
            log_label = CLIENT_HANDSHAKE_LABEL;
553
            /*
554
             * The handshake hash used for the server read/client write handshake
555
             * traffic secret is the same as the hash for the server
556
             * write/client read handshake traffic secret. However, if we
557
             * processed early data then we delay changing the server
558
             * read/client write cipher state until later, and the handshake
559
             * hashes have moved on. Therefore we use the value saved earlier
560
             * when we did the server write/client read change cipher state.
561
             */
562
896
            hash = s->handshake_traffic_hash;
563
896
        } else {
564
0
            insecret = s->master_secret;
565
0
            label = client_application_traffic;
566
0
            labellen = sizeof(client_application_traffic) - 1;
567
0
            log_label = CLIENT_APPLICATION_LABEL;
568
            /*
569
             * For this we only use the handshake hashes up until the server
570
             * Finished hash. We do not include the client's Finished, which is
571
             * what ssl_handshake_hash() would give us. Instead we use the
572
             * previously saved value.
573
             */
574
0
            hash = s->server_finished_hash;
575
0
        }
576
1.98k
    } else {
577
        /* Early data never applies to client-read/server-write */
578
1.98k
        if (which & SSL3_CC_HANDSHAKE) {
579
1.09k
            insecret = s->handshake_secret;
580
1.09k
            finsecret = s->server_finished_secret;
581
1.09k
            finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
582
1.09k
            label = server_handshake_traffic;
583
1.09k
            labellen = sizeof(server_handshake_traffic) - 1;
584
1.09k
            log_label = SERVER_HANDSHAKE_LABEL;
585
1.09k
        } else {
586
896
            insecret = s->master_secret;
587
896
            label = server_application_traffic;
588
896
            labellen = sizeof(server_application_traffic) - 1;
589
896
            log_label = SERVER_APPLICATION_LABEL;
590
896
        }
591
1.98k
    }
592
593
2.88k
    if (!(which & SSL3_CC_EARLY)) {
594
2.88k
        md = ssl_handshake_md(s);
595
2.88k
        cipher = s->s3.tmp.new_sym_enc;
596
2.88k
        if (!ssl3_digest_cached_records(s, 1)
597
2.88k
                || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
598
0
            /* SSLfatal() already called */;
599
0
            goto err;
600
0
        }
601
2.88k
    }
602
603
    /*
604
     * Save the hash of handshakes up to now for use when we calculate the
605
     * client application traffic secret
606
     */
607
2.88k
    if (label == server_application_traffic)
608
896
        memcpy(s->server_finished_hash, hashval, hashlen);
609
610
2.88k
    if (label == server_handshake_traffic)
611
1.09k
        memcpy(s->handshake_traffic_hash, hashval, hashlen);
612
613
2.88k
    if (label == client_application_traffic) {
614
        /*
615
         * We also create the resumption master secret, but this time use the
616
         * hash for the whole handshake including the Client Finished
617
         */
618
0
        if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
619
0
                               resumption_master_secret,
620
0
                               sizeof(resumption_master_secret) - 1,
621
0
                               hashval, hashlen, s->resumption_master_secret,
622
0
                               hashlen, 1)) {
623
            /* SSLfatal() already called */
624
0
            goto err;
625
0
        }
626
0
    }
627
628
    /* check whether cipher is known */
629
2.88k
    if(!ossl_assert(cipher != NULL))
630
0
        goto err;
631
632
2.88k
    if (!derive_secret_key_and_iv(s, which & SSL3_CC_WRITE, md, cipher,
633
2.88k
                                  insecret, hash, label, labellen, secret, key,
634
2.88k
                                  iv, ciph_ctx)) {
635
        /* SSLfatal() already called */
636
0
        goto err;
637
0
    }
638
639
2.88k
    if (label == server_application_traffic) {
640
896
        memcpy(s->server_app_traffic_secret, secret, hashlen);
641
        /* Now we create the exporter master secret */
642
896
        if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
643
896
                               exporter_master_secret,
644
896
                               sizeof(exporter_master_secret) - 1,
645
896
                               hash, hashlen, s->exporter_master_secret,
646
896
                               hashlen, 1)) {
647
            /* SSLfatal() already called */
648
0
            goto err;
649
0
        }
650
651
896
        if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
652
896
                            hashlen)) {
653
            /* SSLfatal() already called */
654
0
            goto err;
655
0
        }
656
1.98k
    } else if (label == client_application_traffic)
657
0
        memcpy(s->client_app_traffic_secret, secret, hashlen);
658
659
2.88k
    if (!ssl_log_secret(s, log_label, secret, hashlen)) {
660
        /* SSLfatal() already called */
661
0
        goto err;
662
0
    }
663
664
2.88k
    if (finsecret != NULL
665
2.88k
            && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
666
1.98k
                                         finsecret, finsecretlen)) {
667
        /* SSLfatal() already called */
668
0
        goto err;
669
0
    }
670
671
2.88k
    if (!s->server && label == client_early_traffic)
672
0
        s->statem.enc_write_state = ENC_WRITE_STATE_WRITE_PLAIN_ALERTS;
673
2.88k
    else
674
2.88k
        s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
675
#ifndef OPENSSL_NO_KTLS
676
# if defined(OPENSSL_KTLS_TLS13)
677
    if (!(which & SSL3_CC_WRITE)
678
            || !(which & SSL3_CC_APPLICATION)
679
            || (s->options & SSL_OP_ENABLE_KTLS) == 0)
680
        goto skip_ktls;
681
682
    /* ktls supports only the maximum fragment size */
683
    if (ssl_get_max_send_fragment(s) != SSL3_RT_MAX_PLAIN_LENGTH)
684
        goto skip_ktls;
685
686
    /* ktls does not support record padding */
687
    if (s->record_padding_cb != NULL)
688
        goto skip_ktls;
689
690
    /* check that cipher is supported */
691
    if (!ktls_check_supported_cipher(s, cipher, ciph_ctx))
692
        goto skip_ktls;
693
694
    bio = s->wbio;
695
696
    if (!ossl_assert(bio != NULL)) {
697
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
698
        goto err;
699
    }
700
701
    /* All future data will get encrypted by ktls. Flush the BIO or skip ktls */
702
    if (BIO_flush(bio) <= 0)
703
        goto skip_ktls;
704
705
    /* configure kernel crypto structure */
706
    if (!ktls_configure_crypto(s, cipher, ciph_ctx,
707
                               RECORD_LAYER_get_write_sequence(&s->rlayer),
708
                               &crypto_info, NULL, iv, key, NULL, 0))
709
        goto skip_ktls;
710
711
    /* ktls works with user provided buffers directly */
712
    if (BIO_set_ktls(bio, &crypto_info, which & SSL3_CC_WRITE))
713
        ssl3_release_write_buffer(s);
714
skip_ktls:
715
# endif
716
#endif
717
2.88k
    ret = 1;
718
2.88k
 err:
719
2.88k
    if ((which & SSL3_CC_EARLY) != 0) {
720
        /* We up-refed this so now we need to down ref */
721
0
        ssl_evp_cipher_free(cipher);
722
0
    }
723
2.88k
    OPENSSL_cleanse(key, sizeof(key));
724
2.88k
    OPENSSL_cleanse(secret, sizeof(secret));
725
2.88k
    return ret;
726
2.88k
}
727
728
int tls13_update_key(SSL *s, int sending)
729
0
{
730
    /* ASCII: "traffic upd", in hex for EBCDIC compatibility */
731
0
    static const unsigned char application_traffic[] = "\x74\x72\x61\x66\x66\x69\x63\x20\x75\x70\x64";
732
0
    const EVP_MD *md = ssl_handshake_md(s);
733
0
    size_t hashlen;
734
0
    unsigned char key[EVP_MAX_KEY_LENGTH];
735
0
    unsigned char *insecret, *iv;
736
0
    unsigned char secret[EVP_MAX_MD_SIZE];
737
0
    char *log_label;
738
0
    EVP_CIPHER_CTX *ciph_ctx;
739
0
    int ret = 0, l;
740
741
0
    if ((l = EVP_MD_get_size(md)) <= 0) {
742
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
743
0
        return 0;
744
0
    }
745
0
    hashlen = (size_t)l;
746
747
0
    if (s->server == sending)
748
0
        insecret = s->server_app_traffic_secret;
749
0
    else
750
0
        insecret = s->client_app_traffic_secret;
751
752
0
    if (sending) {
753
0
        s->statem.enc_write_state = ENC_WRITE_STATE_INVALID;
754
0
        iv = s->write_iv;
755
0
        ciph_ctx = s->enc_write_ctx;
756
0
        RECORD_LAYER_reset_write_sequence(&s->rlayer);
757
0
    } else {
758
0
        iv = s->read_iv;
759
0
        ciph_ctx = s->enc_read_ctx;
760
0
        RECORD_LAYER_reset_read_sequence(&s->rlayer);
761
0
    }
762
763
0
    if (!derive_secret_key_and_iv(s, sending, md,
764
0
                                  s->s3.tmp.new_sym_enc, insecret, NULL,
765
0
                                  application_traffic,
766
0
                                  sizeof(application_traffic) - 1, secret, key,
767
0
                                  iv, ciph_ctx)) {
768
        /* SSLfatal() already called */
769
0
        goto err;
770
0
    }
771
772
0
    memcpy(insecret, secret, hashlen);
773
774
    /* Call Key log on successful traffic secret update */
775
0
    log_label = s->server == sending ? SERVER_APPLICATION_N_LABEL : CLIENT_APPLICATION_N_LABEL;
776
0
    if (!ssl_log_secret(s, log_label, secret, hashlen)) {
777
        /* SSLfatal() already called */
778
0
        goto err;
779
0
    }
780
781
0
    s->statem.enc_write_state = ENC_WRITE_STATE_VALID;
782
0
    ret = 1;
783
0
 err:
784
0
    OPENSSL_cleanse(key, sizeof(key));
785
0
    OPENSSL_cleanse(secret, sizeof(secret));
786
0
    return ret;
787
0
}
788
789
int tls13_alert_code(int code)
790
7.51k
{
791
    /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
792
7.51k
    if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
793
121
        return code;
794
795
7.39k
    return tls1_alert_code(code);
796
7.51k
}
797
798
int tls13_export_keying_material(SSL *s, unsigned char *out, size_t olen,
799
                                 const char *label, size_t llen,
800
                                 const unsigned char *context,
801
                                 size_t contextlen, int use_context)
802
0
{
803
0
    unsigned char exportsecret[EVP_MAX_MD_SIZE];
804
    /* ASCII: "exporter", in hex for EBCDIC compatibility */
805
0
    static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
806
0
    unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
807
0
    const EVP_MD *md = ssl_handshake_md(s);
808
0
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
809
0
    unsigned int hashsize, datalen;
810
0
    int ret = 0;
811
812
0
    if (ctx == NULL || md == NULL || !ossl_statem_export_allowed(s))
813
0
        goto err;
814
815
0
    if (!use_context)
816
0
        contextlen = 0;
817
818
0
    if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
819
0
            || EVP_DigestUpdate(ctx, context, contextlen) <= 0
820
0
            || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
821
0
            || EVP_DigestInit_ex(ctx, md, NULL) <= 0
822
0
            || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
823
0
            || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
824
0
                                  (const unsigned char *)label, llen,
825
0
                                  data, datalen, exportsecret, hashsize, 0)
826
0
            || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
827
0
                                  sizeof(exporterlabel) - 1, hash, hashsize,
828
0
                                  out, olen, 0))
829
0
        goto err;
830
831
0
    ret = 1;
832
0
 err:
833
0
    EVP_MD_CTX_free(ctx);
834
0
    return ret;
835
0
}
836
837
int tls13_export_keying_material_early(SSL *s, unsigned char *out, size_t olen,
838
                                       const char *label, size_t llen,
839
                                       const unsigned char *context,
840
                                       size_t contextlen)
841
0
{
842
    /* ASCII: "exporter", in hex for EBCDIC compatibility */
843
0
    static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
844
0
    unsigned char exportsecret[EVP_MAX_MD_SIZE];
845
0
    unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
846
0
    const EVP_MD *md;
847
0
    EVP_MD_CTX *ctx = EVP_MD_CTX_new();
848
0
    unsigned int hashsize, datalen;
849
0
    int ret = 0;
850
0
    const SSL_CIPHER *sslcipher;
851
852
0
    if (ctx == NULL || !ossl_statem_export_early_allowed(s))
853
0
        goto err;
854
855
0
    if (!s->server && s->max_early_data > 0
856
0
            && s->session->ext.max_early_data == 0)
857
0
        sslcipher = SSL_SESSION_get0_cipher(s->psksession);
858
0
    else
859
0
        sslcipher = SSL_SESSION_get0_cipher(s->session);
860
861
0
    md = ssl_md(s->ctx, sslcipher->algorithm2);
862
863
    /*
864
     * Calculate the hash value and store it in |data|. The reason why
865
     * the empty string is used is that the definition of TLS-Exporter
866
     * is like so:
867
     *
868
     * TLS-Exporter(label, context_value, key_length) =
869
     *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
870
     *                       "exporter", Hash(context_value), key_length)
871
     *
872
     * Derive-Secret(Secret, Label, Messages) =
873
     *       HKDF-Expand-Label(Secret, Label,
874
     *                         Transcript-Hash(Messages), Hash.length)
875
     *
876
     * Here Transcript-Hash is the cipher suite hash algorithm.
877
     */
878
0
    if (md == NULL
879
0
            || EVP_DigestInit_ex(ctx, md, NULL) <= 0
880
0
            || EVP_DigestUpdate(ctx, context, contextlen) <= 0
881
0
            || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
882
0
            || EVP_DigestInit_ex(ctx, md, NULL) <= 0
883
0
            || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
884
0
            || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
885
0
                                  (const unsigned char *)label, llen,
886
0
                                  data, datalen, exportsecret, hashsize, 0)
887
0
            || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
888
0
                                  sizeof(exporterlabel) - 1, hash, hashsize,
889
0
                                  out, olen, 0))
890
0
        goto err;
891
892
0
    ret = 1;
893
0
 err:
894
0
    EVP_MD_CTX_free(ctx);
895
0
    return ret;
896
0
}