Coverage Report

Created: 2025-07-11 06:57

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