1 /*
2  *  TLS 1.3 key schedule
3  *
4  *  Copyright The Mbed TLS Contributors
5  *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6  */
7 
8 #include "common.h"
9 
10 #if defined(MBEDTLS_SSL_PROTO_TLS1_3)
11 
12 #include <stdint.h>
13 #include <string.h>
14 
15 #include "mbedtls/hkdf.h"
16 #include "debug_internal.h"
17 #include "mbedtls/error.h"
18 #include "mbedtls/platform.h"
19 
20 #include "ssl_misc.h"
21 #include "ssl_tls13_keys.h"
22 #include "ssl_tls13_invasive.h"
23 
24 #include "psa/crypto.h"
25 #include "mbedtls/psa_util.h"
26 
27 /* Define a local translating function to save code size by not using too many
28  * arguments in each translating place. */
local_err_translation(psa_status_t status)29 static int local_err_translation(psa_status_t status)
30 {
31     return psa_status_to_mbedtls(status, psa_to_ssl_errors,
32                                  ARRAY_LENGTH(psa_to_ssl_errors),
33                                  psa_generic_status_to_mbedtls);
34 }
35 #define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
36 
37 #define MBEDTLS_SSL_TLS1_3_LABEL(name, string)       \
38     .name = string,
39 
40 struct mbedtls_ssl_tls13_labels_struct const mbedtls_ssl_tls13_labels =
41 {
42     /* This seems to work in C, despite the string literal being one
43      * character too long due to the 0-termination. */
44     MBEDTLS_SSL_TLS1_3_LABEL_LIST
45 };
46 
47 #undef MBEDTLS_SSL_TLS1_3_LABEL
48 
49 /*
50  * This function creates a HkdfLabel structure used in the TLS 1.3 key schedule.
51  *
52  * The HkdfLabel is specified in RFC 8446 as follows:
53  *
54  * struct HkdfLabel {
55  *   uint16 length;            // Length of expanded key material
56  *   opaque label<7..255>;     // Always prefixed by "tls13 "
57  *   opaque context<0..255>;   // Usually a communication transcript hash
58  * };
59  *
60  * Parameters:
61  * - desired_length: Length of expanded key material
62  *                   Even though the standard allows expansion to up to
63  *                   2**16 Bytes, TLS 1.3 never uses expansion to more than
64  *                   255 Bytes, so we require `desired_length` to be at most
65  *                   255. This allows us to save a few Bytes of code by
66  *                   hardcoding the writing of the high bytes.
67  * - (label, label_len): label + label length, without "tls13 " prefix
68  *                       The label length MUST be less than or equal to
69  *                       MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN
70  *                       It is the caller's responsibility to ensure this.
71  *                       All (label, label length) pairs used in TLS 1.3
72  *                       can be obtained via MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN().
73  * - (ctx, ctx_len): context + context length
74  *                   The context length MUST be less than or equal to
75  *                   MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN
76  *                   It is the caller's responsibility to ensure this.
77  * - dst: Target buffer for HkdfLabel structure,
78  *        This MUST be a writable buffer of size
79  *        at least SSL_TLS1_3_KEY_SCHEDULE_MAX_HKDF_LABEL_LEN Bytes.
80  * - dst_len: Pointer at which to store the actual length of
81  *            the HkdfLabel structure on success.
82  */
83 
84 static const char tls13_label_prefix[6] = "tls13 ";
85 
86 #define SSL_TLS1_3_KEY_SCHEDULE_HKDF_LABEL_LEN(label_len, context_len) \
87     (2                     /* expansion length           */ \
88      + 1                   /* label length               */ \
89      + label_len                                           \
90      + 1                   /* context length             */ \
91      + context_len)
92 
93 #define SSL_TLS1_3_KEY_SCHEDULE_MAX_HKDF_LABEL_LEN                      \
94     SSL_TLS1_3_KEY_SCHEDULE_HKDF_LABEL_LEN(                             \
95         sizeof(tls13_label_prefix) +                       \
96         MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN,     \
97         MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN)
98 
ssl_tls13_hkdf_encode_label(size_t desired_length,const unsigned char * label,size_t label_len,const unsigned char * ctx,size_t ctx_len,unsigned char * dst,size_t * dst_len)99 static void ssl_tls13_hkdf_encode_label(
100     size_t desired_length,
101     const unsigned char *label, size_t label_len,
102     const unsigned char *ctx, size_t ctx_len,
103     unsigned char *dst, size_t *dst_len)
104 {
105     size_t total_label_len =
106         sizeof(tls13_label_prefix) + label_len;
107     size_t total_hkdf_lbl_len =
108         SSL_TLS1_3_KEY_SCHEDULE_HKDF_LABEL_LEN(total_label_len, ctx_len);
109 
110     unsigned char *p = dst;
111 
112     /* Add the size of the expanded key material.
113      * We're hardcoding the high byte to 0 here assuming that we never use
114      * TLS 1.3 HKDF key expansion to more than 255 Bytes. */
115 #if MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN > 255
116 #error "The implementation of ssl_tls13_hkdf_encode_label() is not fit for the \
117     value of MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN"
118 #endif
119 
120     *p++ = 0;
121     *p++ = MBEDTLS_BYTE_0(desired_length);
122 
123     /* Add label incl. prefix */
124     *p++ = MBEDTLS_BYTE_0(total_label_len);
125     memcpy(p, tls13_label_prefix, sizeof(tls13_label_prefix));
126     p += sizeof(tls13_label_prefix);
127     memcpy(p, label, label_len);
128     p += label_len;
129 
130     /* Add context value */
131     *p++ = MBEDTLS_BYTE_0(ctx_len);
132     if (ctx_len != 0) {
133         memcpy(p, ctx, ctx_len);
134     }
135 
136     /* Return total length to the caller.  */
137     *dst_len = total_hkdf_lbl_len;
138 }
139 
mbedtls_ssl_tls13_hkdf_expand_label(psa_algorithm_t hash_alg,const unsigned char * secret,size_t secret_len,const unsigned char * label,size_t label_len,const unsigned char * ctx,size_t ctx_len,unsigned char * buf,size_t buf_len)140 int mbedtls_ssl_tls13_hkdf_expand_label(
141     psa_algorithm_t hash_alg,
142     const unsigned char *secret, size_t secret_len,
143     const unsigned char *label, size_t label_len,
144     const unsigned char *ctx, size_t ctx_len,
145     unsigned char *buf, size_t buf_len)
146 {
147     unsigned char hkdf_label[SSL_TLS1_3_KEY_SCHEDULE_MAX_HKDF_LABEL_LEN];
148     size_t hkdf_label_len = 0;
149     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
150     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
151     psa_key_derivation_operation_t operation =
152         PSA_KEY_DERIVATION_OPERATION_INIT;
153 
154     if (label_len > MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_LABEL_LEN) {
155         /* Should never happen since this is an internal
156          * function, and we know statically which labels
157          * are allowed. */
158         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
159     }
160 
161     if (ctx_len > MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_CONTEXT_LEN) {
162         /* Should not happen, as above. */
163         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
164     }
165 
166     if (buf_len > MBEDTLS_SSL_TLS1_3_KEY_SCHEDULE_MAX_EXPANSION_LEN) {
167         /* Should not happen, as above. */
168         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
169     }
170 
171     if (!PSA_ALG_IS_HASH(hash_alg)) {
172         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
173     }
174 
175     ssl_tls13_hkdf_encode_label(buf_len,
176                                 label, label_len,
177                                 ctx, ctx_len,
178                                 hkdf_label,
179                                 &hkdf_label_len);
180 
181     status = psa_key_derivation_setup(&operation, PSA_ALG_HKDF_EXPAND(hash_alg));
182 
183     if (status != PSA_SUCCESS) {
184         goto cleanup;
185     }
186 
187     status = psa_key_derivation_input_bytes(&operation,
188                                             PSA_KEY_DERIVATION_INPUT_SECRET,
189                                             secret,
190                                             secret_len);
191 
192     if (status != PSA_SUCCESS) {
193         goto cleanup;
194     }
195 
196     status = psa_key_derivation_input_bytes(&operation,
197                                             PSA_KEY_DERIVATION_INPUT_INFO,
198                                             hkdf_label,
199                                             hkdf_label_len);
200 
201     if (status != PSA_SUCCESS) {
202         goto cleanup;
203     }
204 
205     status = psa_key_derivation_output_bytes(&operation,
206                                              buf,
207                                              buf_len);
208 
209     if (status != PSA_SUCCESS) {
210         goto cleanup;
211     }
212 
213 cleanup:
214     abort_status = psa_key_derivation_abort(&operation);
215     status = (status == PSA_SUCCESS ? abort_status : status);
216     mbedtls_platform_zeroize(hkdf_label, hkdf_label_len);
217     return PSA_TO_MBEDTLS_ERR(status);
218 }
219 
220 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_make_traffic_key(psa_algorithm_t hash_alg,const unsigned char * secret,size_t secret_len,unsigned char * key,size_t key_len,unsigned char * iv,size_t iv_len)221 static int ssl_tls13_make_traffic_key(
222     psa_algorithm_t hash_alg,
223     const unsigned char *secret, size_t secret_len,
224     unsigned char *key, size_t key_len,
225     unsigned char *iv, size_t iv_len)
226 {
227     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
228 
229     ret = mbedtls_ssl_tls13_hkdf_expand_label(
230         hash_alg,
231         secret, secret_len,
232         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(key),
233         NULL, 0,
234         key, key_len);
235     if (ret != 0) {
236         return ret;
237     }
238 
239     ret = mbedtls_ssl_tls13_hkdf_expand_label(
240         hash_alg,
241         secret, secret_len,
242         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(iv),
243         NULL, 0,
244         iv, iv_len);
245     return ret;
246 }
247 
248 /*
249  * The traffic keying material is generated from the following inputs:
250  *
251  *  - One secret value per sender.
252  *  - A purpose value indicating the specific value being generated
253  *  - The desired lengths of key and IV.
254  *
255  * The expansion itself is based on HKDF:
256  *
257  *   [sender]_write_key = HKDF-Expand-Label( Secret, "key", "", key_length )
258  *   [sender]_write_iv  = HKDF-Expand-Label( Secret, "iv" , "", iv_length )
259  *
260  * [sender] denotes the sending side and the Secret value is provided
261  * by the function caller. Note that we generate server and client side
262  * keys in a single function call.
263  */
mbedtls_ssl_tls13_make_traffic_keys(psa_algorithm_t hash_alg,const unsigned char * client_secret,const unsigned char * server_secret,size_t secret_len,size_t key_len,size_t iv_len,mbedtls_ssl_key_set * keys)264 int mbedtls_ssl_tls13_make_traffic_keys(
265     psa_algorithm_t hash_alg,
266     const unsigned char *client_secret,
267     const unsigned char *server_secret, size_t secret_len,
268     size_t key_len, size_t iv_len,
269     mbedtls_ssl_key_set *keys)
270 {
271     int ret = 0;
272 
273     ret = ssl_tls13_make_traffic_key(
274         hash_alg, client_secret, secret_len,
275         keys->client_write_key, key_len,
276         keys->client_write_iv, iv_len);
277     if (ret != 0) {
278         return ret;
279     }
280 
281     ret = ssl_tls13_make_traffic_key(
282         hash_alg, server_secret, secret_len,
283         keys->server_write_key, key_len,
284         keys->server_write_iv, iv_len);
285     if (ret != 0) {
286         return ret;
287     }
288 
289     keys->key_len = key_len;
290     keys->iv_len = iv_len;
291 
292     return 0;
293 }
294 
mbedtls_ssl_tls13_derive_secret(psa_algorithm_t hash_alg,const unsigned char * secret,size_t secret_len,const unsigned char * label,size_t label_len,const unsigned char * ctx,size_t ctx_len,int ctx_hashed,unsigned char * dstbuf,size_t dstbuf_len)295 int mbedtls_ssl_tls13_derive_secret(
296     psa_algorithm_t hash_alg,
297     const unsigned char *secret, size_t secret_len,
298     const unsigned char *label, size_t label_len,
299     const unsigned char *ctx, size_t ctx_len,
300     int ctx_hashed,
301     unsigned char *dstbuf, size_t dstbuf_len)
302 {
303     int ret;
304     unsigned char hashed_context[PSA_HASH_MAX_SIZE];
305     if (ctx_hashed == MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED) {
306         psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
307 
308         status = psa_hash_compute(hash_alg, ctx, ctx_len, hashed_context,
309                                   PSA_HASH_LENGTH(hash_alg), &ctx_len);
310         if (status != PSA_SUCCESS) {
311             ret = PSA_TO_MBEDTLS_ERR(status);
312             return ret;
313         }
314     } else {
315         if (ctx_len > sizeof(hashed_context)) {
316             /* This should never happen since this function is internal
317              * and the code sets `ctx_hashed` correctly.
318              * Let's double-check nonetheless to not run at the risk
319              * of getting a stack overflow. */
320             return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
321         }
322 
323         memcpy(hashed_context, ctx, ctx_len);
324     }
325 
326     return mbedtls_ssl_tls13_hkdf_expand_label(hash_alg,
327                                                secret, secret_len,
328                                                label, label_len,
329                                                hashed_context, ctx_len,
330                                                dstbuf, dstbuf_len);
331 
332 }
333 
mbedtls_ssl_tls13_evolve_secret(psa_algorithm_t hash_alg,const unsigned char * secret_old,const unsigned char * input,size_t input_len,unsigned char * secret_new)334 int mbedtls_ssl_tls13_evolve_secret(
335     psa_algorithm_t hash_alg,
336     const unsigned char *secret_old,
337     const unsigned char *input, size_t input_len,
338     unsigned char *secret_new)
339 {
340     int ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
341     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
342     psa_status_t abort_status = PSA_ERROR_CORRUPTION_DETECTED;
343     size_t hlen;
344     unsigned char tmp_secret[PSA_MAC_MAX_SIZE] = { 0 };
345     const unsigned char all_zeroes_input[MBEDTLS_TLS1_3_MD_MAX_SIZE] = { 0 };
346     const unsigned char *l_input = NULL;
347     size_t l_input_len;
348 
349     psa_key_derivation_operation_t operation =
350         PSA_KEY_DERIVATION_OPERATION_INIT;
351 
352     if (!PSA_ALG_IS_HASH(hash_alg)) {
353         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
354     }
355 
356     hlen = PSA_HASH_LENGTH(hash_alg);
357 
358     /* For non-initial runs, call Derive-Secret( ., "derived", "")
359      * on the old secret. */
360     if (secret_old != NULL) {
361         ret = mbedtls_ssl_tls13_derive_secret(
362             hash_alg,
363             secret_old, hlen,
364             MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(derived),
365             NULL, 0,        /* context */
366             MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED,
367             tmp_secret, hlen);
368         if (ret != 0) {
369             goto cleanup;
370         }
371     }
372 
373     ret = 0;
374 
375     if (input != NULL && input_len != 0) {
376         l_input = input;
377         l_input_len = input_len;
378     } else {
379         l_input = all_zeroes_input;
380         l_input_len = hlen;
381     }
382 
383     status = psa_key_derivation_setup(&operation,
384                                       PSA_ALG_HKDF_EXTRACT(hash_alg));
385 
386     if (status != PSA_SUCCESS) {
387         goto cleanup;
388     }
389 
390     status = psa_key_derivation_input_bytes(&operation,
391                                             PSA_KEY_DERIVATION_INPUT_SALT,
392                                             tmp_secret,
393                                             hlen);
394 
395     if (status != PSA_SUCCESS) {
396         goto cleanup;
397     }
398 
399     status = psa_key_derivation_input_bytes(&operation,
400                                             PSA_KEY_DERIVATION_INPUT_SECRET,
401                                             l_input, l_input_len);
402 
403     if (status != PSA_SUCCESS) {
404         goto cleanup;
405     }
406 
407     status = psa_key_derivation_output_bytes(&operation,
408                                              secret_new,
409                                              PSA_HASH_LENGTH(hash_alg));
410 
411     if (status != PSA_SUCCESS) {
412         goto cleanup;
413     }
414 
415 cleanup:
416     abort_status = psa_key_derivation_abort(&operation);
417     status = (status == PSA_SUCCESS ? abort_status : status);
418     ret = (ret == 0 ? PSA_TO_MBEDTLS_ERR(status) : ret);
419     mbedtls_platform_zeroize(tmp_secret, sizeof(tmp_secret));
420     return ret;
421 }
422 
mbedtls_ssl_tls13_derive_early_secrets(psa_algorithm_t hash_alg,unsigned char const * early_secret,unsigned char const * transcript,size_t transcript_len,mbedtls_ssl_tls13_early_secrets * derived)423 int mbedtls_ssl_tls13_derive_early_secrets(
424     psa_algorithm_t hash_alg,
425     unsigned char const *early_secret,
426     unsigned char const *transcript, size_t transcript_len,
427     mbedtls_ssl_tls13_early_secrets *derived)
428 {
429     int ret;
430     size_t const hash_len = PSA_HASH_LENGTH(hash_alg);
431 
432     /* We should never call this function with an unknown hash,
433      * but add an assertion anyway. */
434     if (!PSA_ALG_IS_HASH(hash_alg)) {
435         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
436     }
437 
438     /*
439      *            0
440      *            |
441      *            v
442      *  PSK ->  HKDF-Extract = Early Secret
443      *            |
444      *            +-----> Derive-Secret(., "c e traffic", ClientHello)
445      *            |                     = client_early_traffic_secret
446      *            |
447      *            +-----> Derive-Secret(., "e exp master", ClientHello)
448      *            |                     = early_exporter_master_secret
449      *            v
450      */
451 
452     /* Create client_early_traffic_secret */
453     ret = mbedtls_ssl_tls13_derive_secret(
454         hash_alg,
455         early_secret, hash_len,
456         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(c_e_traffic),
457         transcript, transcript_len,
458         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
459         derived->client_early_traffic_secret,
460         hash_len);
461     if (ret != 0) {
462         return ret;
463     }
464 
465     /* Create early exporter */
466     ret = mbedtls_ssl_tls13_derive_secret(
467         hash_alg,
468         early_secret, hash_len,
469         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(e_exp_master),
470         transcript, transcript_len,
471         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
472         derived->early_exporter_master_secret,
473         hash_len);
474     if (ret != 0) {
475         return ret;
476     }
477 
478     return 0;
479 }
480 
mbedtls_ssl_tls13_derive_handshake_secrets(psa_algorithm_t hash_alg,unsigned char const * handshake_secret,unsigned char const * transcript,size_t transcript_len,mbedtls_ssl_tls13_handshake_secrets * derived)481 int mbedtls_ssl_tls13_derive_handshake_secrets(
482     psa_algorithm_t hash_alg,
483     unsigned char const *handshake_secret,
484     unsigned char const *transcript, size_t transcript_len,
485     mbedtls_ssl_tls13_handshake_secrets *derived)
486 {
487     int ret;
488     size_t const hash_len = PSA_HASH_LENGTH(hash_alg);
489 
490     /* We should never call this function with an unknown hash,
491      * but add an assertion anyway. */
492     if (!PSA_ALG_IS_HASH(hash_alg)) {
493         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
494     }
495 
496     /*
497      *
498      * Handshake Secret
499      * |
500      * +-----> Derive-Secret( ., "c hs traffic",
501      * |                     ClientHello...ServerHello )
502      * |                     = client_handshake_traffic_secret
503      * |
504      * +-----> Derive-Secret( ., "s hs traffic",
505      * |                     ClientHello...ServerHello )
506      * |                     = server_handshake_traffic_secret
507      *
508      */
509 
510     /*
511      * Compute client_handshake_traffic_secret with
512      * Derive-Secret( ., "c hs traffic", ClientHello...ServerHello )
513      */
514 
515     ret = mbedtls_ssl_tls13_derive_secret(
516         hash_alg,
517         handshake_secret, hash_len,
518         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(c_hs_traffic),
519         transcript, transcript_len,
520         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
521         derived->client_handshake_traffic_secret,
522         hash_len);
523     if (ret != 0) {
524         return ret;
525     }
526 
527     /*
528      * Compute server_handshake_traffic_secret with
529      * Derive-Secret( ., "s hs traffic", ClientHello...ServerHello )
530      */
531 
532     ret = mbedtls_ssl_tls13_derive_secret(
533         hash_alg,
534         handshake_secret, hash_len,
535         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(s_hs_traffic),
536         transcript, transcript_len,
537         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
538         derived->server_handshake_traffic_secret,
539         hash_len);
540     if (ret != 0) {
541         return ret;
542     }
543 
544     return 0;
545 }
546 
mbedtls_ssl_tls13_derive_application_secrets(psa_algorithm_t hash_alg,unsigned char const * application_secret,unsigned char const * transcript,size_t transcript_len,mbedtls_ssl_tls13_application_secrets * derived)547 int mbedtls_ssl_tls13_derive_application_secrets(
548     psa_algorithm_t hash_alg,
549     unsigned char const *application_secret,
550     unsigned char const *transcript, size_t transcript_len,
551     mbedtls_ssl_tls13_application_secrets *derived)
552 {
553     int ret;
554     size_t const hash_len = PSA_HASH_LENGTH(hash_alg);
555 
556     /* We should never call this function with an unknown hash,
557      * but add an assertion anyway. */
558     if (!PSA_ALG_IS_HASH(hash_alg)) {
559         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
560     }
561 
562     /* Generate {client,server}_application_traffic_secret_0
563      *
564      * Master Secret
565      * |
566      * +-----> Derive-Secret( ., "c ap traffic",
567      * |                      ClientHello...server Finished )
568      * |                      = client_application_traffic_secret_0
569      * |
570      * +-----> Derive-Secret( ., "s ap traffic",
571      * |                      ClientHello...Server Finished )
572      * |                      = server_application_traffic_secret_0
573      * |
574      * +-----> Derive-Secret( ., "exp master",
575      * |                      ClientHello...server Finished)
576      * |                      = exporter_master_secret
577      *
578      */
579 
580     ret = mbedtls_ssl_tls13_derive_secret(
581         hash_alg,
582         application_secret, hash_len,
583         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(c_ap_traffic),
584         transcript, transcript_len,
585         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
586         derived->client_application_traffic_secret_N,
587         hash_len);
588     if (ret != 0) {
589         return ret;
590     }
591 
592     ret = mbedtls_ssl_tls13_derive_secret(
593         hash_alg,
594         application_secret, hash_len,
595         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(s_ap_traffic),
596         transcript, transcript_len,
597         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
598         derived->server_application_traffic_secret_N,
599         hash_len);
600     if (ret != 0) {
601         return ret;
602     }
603 
604     ret = mbedtls_ssl_tls13_derive_secret(
605         hash_alg,
606         application_secret, hash_len,
607         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(exp_master),
608         transcript, transcript_len,
609         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
610         derived->exporter_master_secret,
611         hash_len);
612     if (ret != 0) {
613         return ret;
614     }
615 
616     return 0;
617 }
618 
619 /* Generate resumption_master_secret for use with the ticket exchange.
620  *
621  * This is not integrated with mbedtls_ssl_tls13_derive_application_secrets()
622  * because it uses the transcript hash up to and including ClientFinished. */
mbedtls_ssl_tls13_derive_resumption_master_secret(psa_algorithm_t hash_alg,unsigned char const * application_secret,unsigned char const * transcript,size_t transcript_len,mbedtls_ssl_tls13_application_secrets * derived)623 int mbedtls_ssl_tls13_derive_resumption_master_secret(
624     psa_algorithm_t hash_alg,
625     unsigned char const *application_secret,
626     unsigned char const *transcript, size_t transcript_len,
627     mbedtls_ssl_tls13_application_secrets *derived)
628 {
629     int ret;
630     size_t const hash_len = PSA_HASH_LENGTH(hash_alg);
631 
632     /* We should never call this function with an unknown hash,
633      * but add an assertion anyway. */
634     if (!PSA_ALG_IS_HASH(hash_alg)) {
635         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
636     }
637 
638     ret = mbedtls_ssl_tls13_derive_secret(
639         hash_alg,
640         application_secret, hash_len,
641         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(res_master),
642         transcript, transcript_len,
643         MBEDTLS_SSL_TLS1_3_CONTEXT_HASHED,
644         derived->resumption_master_secret,
645         hash_len);
646 
647     if (ret != 0) {
648         return ret;
649     }
650 
651     return 0;
652 }
653 
654 /**
655  * \brief Transition into application stage of TLS 1.3 key schedule.
656  *
657  *        The TLS 1.3 key schedule can be viewed as a simple state machine
658  *        with states Initial -> Early -> Handshake -> Application, and
659  *        this function represents the Handshake -> Application transition.
660  *
661  *        In the handshake stage, ssl_tls13_generate_application_keys()
662  *        can be used to derive the handshake traffic keys.
663  *
664  * \param ssl  The SSL context to operate on. This must be in key schedule
665  *             stage \c Handshake.
666  *
667  * \returns    \c 0 on success.
668  * \returns    A negative error code on failure.
669  */
670 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_key_schedule_stage_application(mbedtls_ssl_context * ssl)671 static int ssl_tls13_key_schedule_stage_application(mbedtls_ssl_context *ssl)
672 {
673     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
674     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
675     psa_algorithm_t const hash_alg = mbedtls_md_psa_alg_from_type(
676         (mbedtls_md_type_t) handshake->ciphersuite_info->mac);
677 
678     /*
679      * Compute MasterSecret
680      */
681     ret = mbedtls_ssl_tls13_evolve_secret(
682         hash_alg,
683         handshake->tls13_master_secrets.handshake,
684         NULL, 0,
685         handshake->tls13_master_secrets.app);
686     if (ret != 0) {
687         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_evolve_secret", ret);
688         return ret;
689     }
690 
691     MBEDTLS_SSL_DEBUG_BUF(
692         4, "Master secret",
693         handshake->tls13_master_secrets.app, PSA_HASH_LENGTH(hash_alg));
694 
695     return 0;
696 }
697 
698 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_calc_finished_core(psa_algorithm_t hash_alg,unsigned char const * base_key,unsigned char const * transcript,unsigned char * dst,size_t * dst_len)699 static int ssl_tls13_calc_finished_core(psa_algorithm_t hash_alg,
700                                         unsigned char const *base_key,
701                                         unsigned char const *transcript,
702                                         unsigned char *dst,
703                                         size_t *dst_len)
704 {
705     mbedtls_svc_key_id_t key = MBEDTLS_SVC_KEY_ID_INIT;
706     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
707     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
708     size_t hash_len = PSA_HASH_LENGTH(hash_alg);
709     unsigned char finished_key[PSA_MAC_MAX_SIZE];
710     int ret;
711     psa_algorithm_t alg;
712 
713     /* We should never call this function with an unknown hash,
714      * but add an assertion anyway. */
715     if (!PSA_ALG_IS_HASH(hash_alg)) {
716         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
717     }
718 
719     /* TLS 1.3 Finished message
720      *
721      * struct {
722      *     opaque verify_data[Hash.length];
723      * } Finished;
724      *
725      * verify_data =
726      *     HMAC( finished_key,
727      *            Hash( Handshake Context +
728      *                  Certificate*      +
729      *                  CertificateVerify* )
730      *    )
731      *
732      * finished_key =
733      *    HKDF-Expand-Label( BaseKey, "finished", "", Hash.length )
734      */
735 
736     ret = mbedtls_ssl_tls13_hkdf_expand_label(
737         hash_alg, base_key, hash_len,
738         MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(finished),
739         NULL, 0,
740         finished_key, hash_len);
741     if (ret != 0) {
742         goto exit;
743     }
744 
745     alg = PSA_ALG_HMAC(hash_alg);
746     psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_MESSAGE);
747     psa_set_key_algorithm(&attributes, alg);
748     psa_set_key_type(&attributes, PSA_KEY_TYPE_HMAC);
749 
750     status = psa_import_key(&attributes, finished_key, hash_len, &key);
751     if (status != PSA_SUCCESS) {
752         ret = PSA_TO_MBEDTLS_ERR(status);
753         goto exit;
754     }
755 
756     status = psa_mac_compute(key, alg, transcript, hash_len,
757                              dst, hash_len, dst_len);
758     ret = PSA_TO_MBEDTLS_ERR(status);
759 
760 exit:
761 
762     status = psa_destroy_key(key);
763     if (ret == 0) {
764         ret = PSA_TO_MBEDTLS_ERR(status);
765     }
766 
767     mbedtls_platform_zeroize(finished_key, sizeof(finished_key));
768 
769     return ret;
770 }
771 
mbedtls_ssl_tls13_calculate_verify_data(mbedtls_ssl_context * ssl,unsigned char * dst,size_t dst_len,size_t * actual_len,int from)772 int mbedtls_ssl_tls13_calculate_verify_data(mbedtls_ssl_context *ssl,
773                                             unsigned char *dst,
774                                             size_t dst_len,
775                                             size_t *actual_len,
776                                             int from)
777 {
778     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
779 
780     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
781     size_t transcript_len;
782 
783     unsigned char *base_key = NULL;
784     size_t base_key_len = 0;
785     mbedtls_ssl_tls13_handshake_secrets *tls13_hs_secrets =
786         &ssl->handshake->tls13_hs_secrets;
787 
788     mbedtls_md_type_t const md_type = (mbedtls_md_type_t) ssl->handshake->ciphersuite_info->mac;
789 
790     psa_algorithm_t hash_alg = mbedtls_md_psa_alg_from_type(
791         (mbedtls_md_type_t) ssl->handshake->ciphersuite_info->mac);
792     size_t const hash_len = PSA_HASH_LENGTH(hash_alg);
793 
794     MBEDTLS_SSL_DEBUG_MSG(2, ("=> mbedtls_ssl_tls13_calculate_verify_data"));
795 
796     if (from == MBEDTLS_SSL_IS_CLIENT) {
797         base_key = tls13_hs_secrets->client_handshake_traffic_secret;
798         base_key_len = sizeof(tls13_hs_secrets->client_handshake_traffic_secret);
799     } else {
800         base_key = tls13_hs_secrets->server_handshake_traffic_secret;
801         base_key_len = sizeof(tls13_hs_secrets->server_handshake_traffic_secret);
802     }
803 
804     if (dst_len < hash_len) {
805         ret = MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
806         goto exit;
807     }
808 
809     ret = mbedtls_ssl_get_handshake_transcript(ssl, md_type,
810                                                transcript, sizeof(transcript),
811                                                &transcript_len);
812     if (ret != 0) {
813         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_get_handshake_transcript", ret);
814         goto exit;
815     }
816     MBEDTLS_SSL_DEBUG_BUF(4, "handshake hash", transcript, transcript_len);
817 
818     ret = ssl_tls13_calc_finished_core(hash_alg, base_key,
819                                        transcript, dst, actual_len);
820     if (ret != 0) {
821         goto exit;
822     }
823 
824     MBEDTLS_SSL_DEBUG_BUF(3, "verify_data for finished message", dst, hash_len);
825     MBEDTLS_SSL_DEBUG_MSG(2, ("<= mbedtls_ssl_tls13_calculate_verify_data"));
826 
827 exit:
828     /* Erase handshake secrets */
829     mbedtls_platform_zeroize(base_key, base_key_len);
830     mbedtls_platform_zeroize(transcript, sizeof(transcript));
831     return ret;
832 }
833 
mbedtls_ssl_tls13_create_psk_binder(mbedtls_ssl_context * ssl,const psa_algorithm_t hash_alg,unsigned char const * psk,size_t psk_len,int psk_type,unsigned char const * transcript,unsigned char * result)834 int mbedtls_ssl_tls13_create_psk_binder(mbedtls_ssl_context *ssl,
835                                         const psa_algorithm_t hash_alg,
836                                         unsigned char const *psk, size_t psk_len,
837                                         int psk_type,
838                                         unsigned char const *transcript,
839                                         unsigned char *result)
840 {
841     int ret = 0;
842     unsigned char binder_key[PSA_MAC_MAX_SIZE];
843     unsigned char early_secret[PSA_MAC_MAX_SIZE];
844     size_t const hash_len = PSA_HASH_LENGTH(hash_alg);
845     size_t actual_len;
846 
847 #if !defined(MBEDTLS_DEBUG_C)
848     ssl = NULL; /* make sure we don't use it except for debug */
849     ((void) ssl);
850 #endif
851 
852     /* We should never call this function with an unknown hash,
853      * but add an assertion anyway. */
854     if (!PSA_ALG_IS_HASH(hash_alg)) {
855         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
856     }
857 
858     /*
859      *            0
860      *            |
861      *            v
862      *  PSK ->  HKDF-Extract = Early Secret
863      *            |
864      *            +-----> Derive-Secret(., "ext binder" | "res binder", "")
865      *            |                     = binder_key
866      *            v
867      */
868 
869     ret = mbedtls_ssl_tls13_evolve_secret(hash_alg,
870                                           NULL,           /* Old secret */
871                                           psk, psk_len,   /* Input      */
872                                           early_secret);
873     if (ret != 0) {
874         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_evolve_secret", ret);
875         goto exit;
876     }
877 
878     MBEDTLS_SSL_DEBUG_BUF(4, "mbedtls_ssl_tls13_create_psk_binder",
879                           early_secret, hash_len);
880 
881     if (psk_type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION) {
882         ret = mbedtls_ssl_tls13_derive_secret(
883             hash_alg,
884             early_secret, hash_len,
885             MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(res_binder),
886             NULL, 0, MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED,
887             binder_key, hash_len);
888         MBEDTLS_SSL_DEBUG_MSG(4, ("Derive Early Secret with 'res binder'"));
889     } else {
890         ret = mbedtls_ssl_tls13_derive_secret(
891             hash_alg,
892             early_secret, hash_len,
893             MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(ext_binder),
894             NULL, 0, MBEDTLS_SSL_TLS1_3_CONTEXT_UNHASHED,
895             binder_key, hash_len);
896         MBEDTLS_SSL_DEBUG_MSG(4, ("Derive Early Secret with 'ext binder'"));
897     }
898 
899     if (ret != 0) {
900         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_derive_secret", ret);
901         goto exit;
902     }
903 
904     /*
905      * The binding_value is computed in the same way as the Finished message
906      * but with the BaseKey being the binder_key.
907      */
908 
909     ret = ssl_tls13_calc_finished_core(hash_alg, binder_key, transcript,
910                                        result, &actual_len);
911     if (ret != 0) {
912         goto exit;
913     }
914 
915     MBEDTLS_SSL_DEBUG_BUF(3, "psk binder", result, actual_len);
916 
917 exit:
918 
919     mbedtls_platform_zeroize(early_secret, sizeof(early_secret));
920     mbedtls_platform_zeroize(binder_key,   sizeof(binder_key));
921     return ret;
922 }
923 
mbedtls_ssl_tls13_populate_transform(mbedtls_ssl_transform * transform,int endpoint,int ciphersuite,mbedtls_ssl_key_set const * traffic_keys,mbedtls_ssl_context * ssl)924 int mbedtls_ssl_tls13_populate_transform(
925     mbedtls_ssl_transform *transform,
926     int endpoint, int ciphersuite,
927     mbedtls_ssl_key_set const *traffic_keys,
928     mbedtls_ssl_context *ssl /* DEBUG ONLY */)
929 {
930 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
931     int ret;
932     mbedtls_cipher_info_t const *cipher_info;
933 #endif /* MBEDTLS_USE_PSA_CRYPTO */
934     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
935     unsigned char const *key_enc;
936     unsigned char const *iv_enc;
937     unsigned char const *key_dec;
938     unsigned char const *iv_dec;
939 
940 #if defined(MBEDTLS_USE_PSA_CRYPTO)
941     psa_key_type_t key_type;
942     psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
943     psa_algorithm_t alg;
944     size_t key_bits;
945     psa_status_t status = PSA_SUCCESS;
946 #endif
947 
948 #if !defined(MBEDTLS_DEBUG_C)
949     ssl = NULL; /* make sure we don't use it except for those cases */
950     (void) ssl;
951 #endif
952 
953     ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(ciphersuite);
954     if (ciphersuite_info == NULL) {
955         MBEDTLS_SSL_DEBUG_MSG(1, ("ciphersuite info for %d not found",
956                                   ciphersuite));
957         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
958     }
959 
960 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
961     cipher_info = mbedtls_cipher_info_from_type(ciphersuite_info->cipher);
962     if (cipher_info == NULL) {
963         MBEDTLS_SSL_DEBUG_MSG(1, ("cipher info for %u not found",
964                                   ciphersuite_info->cipher));
965         return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
966     }
967 
968     /*
969      * Setup cipher contexts in target transform
970      */
971     if ((ret = mbedtls_cipher_setup(&transform->cipher_ctx_enc,
972                                     cipher_info)) != 0) {
973         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup", ret);
974         return ret;
975     }
976 
977     if ((ret = mbedtls_cipher_setup(&transform->cipher_ctx_dec,
978                                     cipher_info)) != 0) {
979         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup", ret);
980         return ret;
981     }
982 #endif /* MBEDTLS_USE_PSA_CRYPTO */
983 
984 #if defined(MBEDTLS_SSL_SRV_C)
985     if (endpoint == MBEDTLS_SSL_IS_SERVER) {
986         key_enc = traffic_keys->server_write_key;
987         key_dec = traffic_keys->client_write_key;
988         iv_enc = traffic_keys->server_write_iv;
989         iv_dec = traffic_keys->client_write_iv;
990     } else
991 #endif /* MBEDTLS_SSL_SRV_C */
992 #if defined(MBEDTLS_SSL_CLI_C)
993     if (endpoint == MBEDTLS_SSL_IS_CLIENT) {
994         key_enc = traffic_keys->client_write_key;
995         key_dec = traffic_keys->server_write_key;
996         iv_enc = traffic_keys->client_write_iv;
997         iv_dec = traffic_keys->server_write_iv;
998     } else
999 #endif /* MBEDTLS_SSL_CLI_C */
1000     {
1001         /* should not happen */
1002         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1003     }
1004 
1005     memcpy(transform->iv_enc, iv_enc, traffic_keys->iv_len);
1006     memcpy(transform->iv_dec, iv_dec, traffic_keys->iv_len);
1007 
1008 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
1009     if ((ret = mbedtls_cipher_setkey(&transform->cipher_ctx_enc,
1010                                      key_enc, (int) mbedtls_cipher_info_get_key_bitlen(cipher_info),
1011                                      MBEDTLS_ENCRYPT)) != 0) {
1012         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setkey", ret);
1013         return ret;
1014     }
1015 
1016     if ((ret = mbedtls_cipher_setkey(&transform->cipher_ctx_dec,
1017                                      key_dec, (int) mbedtls_cipher_info_get_key_bitlen(cipher_info),
1018                                      MBEDTLS_DECRYPT)) != 0) {
1019         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setkey", ret);
1020         return ret;
1021     }
1022 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1023 
1024     /*
1025      * Setup other fields in SSL transform
1026      */
1027 
1028     if ((ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG) != 0) {
1029         transform->taglen  = 8;
1030     } else {
1031         transform->taglen  = 16;
1032     }
1033 
1034     transform->ivlen       = traffic_keys->iv_len;
1035     transform->maclen      = 0;
1036     transform->fixed_ivlen = transform->ivlen;
1037     transform->tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
1038 
1039     /* We add the true record content type (1 Byte) to the plaintext and
1040      * then pad to the configured granularity. The minimum length of the
1041      * type-extended and padded plaintext is therefore the padding
1042      * granularity. */
1043     transform->minlen =
1044         transform->taglen + MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY;
1045 
1046 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1047     /*
1048      * Setup psa keys and alg
1049      */
1050     if ((status = mbedtls_ssl_cipher_to_psa((mbedtls_cipher_type_t) ciphersuite_info->cipher,
1051                                             transform->taglen,
1052                                             &alg,
1053                                             &key_type,
1054                                             &key_bits)) != PSA_SUCCESS) {
1055         MBEDTLS_SSL_DEBUG_RET(
1056             1, "mbedtls_ssl_cipher_to_psa", PSA_TO_MBEDTLS_ERR(status));
1057         return PSA_TO_MBEDTLS_ERR(status);
1058     }
1059 
1060     transform->psa_alg = alg;
1061 
1062     if (alg != MBEDTLS_SSL_NULL_CIPHER) {
1063         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_ENCRYPT);
1064         psa_set_key_algorithm(&attributes, alg);
1065         psa_set_key_type(&attributes, key_type);
1066 
1067         if ((status = psa_import_key(&attributes,
1068                                      key_enc,
1069                                      PSA_BITS_TO_BYTES(key_bits),
1070                                      &transform->psa_key_enc)) != PSA_SUCCESS) {
1071             MBEDTLS_SSL_DEBUG_RET(
1072                 1, "psa_import_key", PSA_TO_MBEDTLS_ERR(status));
1073             return PSA_TO_MBEDTLS_ERR(status);
1074         }
1075 
1076         psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_DECRYPT);
1077 
1078         if ((status = psa_import_key(&attributes,
1079                                      key_dec,
1080                                      PSA_BITS_TO_BYTES(key_bits),
1081                                      &transform->psa_key_dec)) != PSA_SUCCESS) {
1082             MBEDTLS_SSL_DEBUG_RET(
1083                 1, "psa_import_key", PSA_TO_MBEDTLS_ERR(status));
1084             return PSA_TO_MBEDTLS_ERR(status);
1085         }
1086     }
1087 #endif /* MBEDTLS_USE_PSA_CRYPTO */
1088 
1089     return 0;
1090 }
1091 
1092 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_get_cipher_key_info(const mbedtls_ssl_ciphersuite_t * ciphersuite_info,size_t * key_len,size_t * iv_len)1093 static int ssl_tls13_get_cipher_key_info(
1094     const mbedtls_ssl_ciphersuite_t *ciphersuite_info,
1095     size_t *key_len, size_t *iv_len)
1096 {
1097     psa_key_type_t key_type;
1098     psa_algorithm_t alg;
1099     size_t taglen;
1100     size_t key_bits;
1101     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1102 
1103     if (ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG) {
1104         taglen = 8;
1105     } else {
1106         taglen = 16;
1107     }
1108 
1109     status = mbedtls_ssl_cipher_to_psa((mbedtls_cipher_type_t) ciphersuite_info->cipher, taglen,
1110                                        &alg, &key_type, &key_bits);
1111     if (status != PSA_SUCCESS) {
1112         return PSA_TO_MBEDTLS_ERR(status);
1113     }
1114 
1115     *key_len = PSA_BITS_TO_BYTES(key_bits);
1116 
1117     /* TLS 1.3 only have AEAD ciphers, IV length is unconditionally 12 bytes */
1118     *iv_len = 12;
1119 
1120     return 0;
1121 }
1122 
1123 #if defined(MBEDTLS_SSL_EARLY_DATA)
1124 /*
1125  * ssl_tls13_generate_early_key() generates the key necessary for protecting
1126  * the early application data and handshake messages as described in section 7
1127  * of RFC 8446.
1128  *
1129  * NOTE: Only one key is generated, the key for the traffic from the client to
1130  *       the server. The TLS 1.3 specification does not define a secret and thus
1131  *       a key for server early traffic.
1132  */
1133 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_generate_early_key(mbedtls_ssl_context * ssl,mbedtls_ssl_key_set * traffic_keys)1134 static int ssl_tls13_generate_early_key(mbedtls_ssl_context *ssl,
1135                                         mbedtls_ssl_key_set *traffic_keys)
1136 {
1137     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1138     mbedtls_md_type_t md_type;
1139     psa_algorithm_t hash_alg;
1140     size_t hash_len;
1141     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1142     size_t transcript_len;
1143     size_t key_len = 0;
1144     size_t iv_len = 0;
1145     mbedtls_ssl_tls13_early_secrets tls13_early_secrets;
1146 
1147     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1148     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
1149         handshake->ciphersuite_info;
1150 
1151     MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_tls13_generate_early_key"));
1152 
1153     ret = ssl_tls13_get_cipher_key_info(ciphersuite_info, &key_len, &iv_len);
1154     if (ret != 0) {
1155         MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_get_cipher_key_info", ret);
1156         goto cleanup;
1157     }
1158 
1159     md_type = (mbedtls_md_type_t) ciphersuite_info->mac;
1160 
1161     hash_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac);
1162     hash_len = PSA_HASH_LENGTH(hash_alg);
1163 
1164     ret = mbedtls_ssl_get_handshake_transcript(ssl, md_type,
1165                                                transcript,
1166                                                sizeof(transcript),
1167                                                &transcript_len);
1168     if (ret != 0) {
1169         MBEDTLS_SSL_DEBUG_RET(1,
1170                               "mbedtls_ssl_get_handshake_transcript",
1171                               ret);
1172         goto cleanup;
1173     }
1174 
1175     ret = mbedtls_ssl_tls13_derive_early_secrets(
1176         hash_alg, handshake->tls13_master_secrets.early,
1177         transcript, transcript_len, &tls13_early_secrets);
1178     if (ret != 0) {
1179         MBEDTLS_SSL_DEBUG_RET(
1180             1, "mbedtls_ssl_tls13_derive_early_secrets", ret);
1181         goto cleanup;
1182     }
1183 
1184     MBEDTLS_SSL_DEBUG_BUF(
1185         4, "Client early traffic secret",
1186         tls13_early_secrets.client_early_traffic_secret, hash_len);
1187 
1188     /*
1189      * Export client handshake traffic secret
1190      */
1191     if (ssl->f_export_keys != NULL) {
1192         ssl->f_export_keys(
1193             ssl->p_export_keys,
1194             MBEDTLS_SSL_KEY_EXPORT_TLS1_3_CLIENT_EARLY_SECRET,
1195             tls13_early_secrets.client_early_traffic_secret,
1196             hash_len,
1197             handshake->randbytes,
1198             handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN,
1199             MBEDTLS_SSL_TLS_PRF_NONE /* TODO: FIX! */);
1200     }
1201 
1202     ret = ssl_tls13_make_traffic_key(
1203         hash_alg,
1204         tls13_early_secrets.client_early_traffic_secret,
1205         hash_len, traffic_keys->client_write_key, key_len,
1206         traffic_keys->client_write_iv, iv_len);
1207     if (ret != 0) {
1208         MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_make_traffic_key", ret);
1209         goto cleanup;
1210     }
1211     traffic_keys->key_len = key_len;
1212     traffic_keys->iv_len = iv_len;
1213 
1214     MBEDTLS_SSL_DEBUG_BUF(4, "client early write_key",
1215                           traffic_keys->client_write_key,
1216                           traffic_keys->key_len);
1217 
1218     MBEDTLS_SSL_DEBUG_BUF(4, "client early write_iv",
1219                           traffic_keys->client_write_iv,
1220                           traffic_keys->iv_len);
1221 
1222     MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_tls13_generate_early_key"));
1223 
1224 cleanup:
1225     /* Erase early secrets and transcript */
1226     mbedtls_platform_zeroize(
1227         &tls13_early_secrets, sizeof(mbedtls_ssl_tls13_early_secrets));
1228     mbedtls_platform_zeroize(transcript, sizeof(transcript));
1229     return ret;
1230 }
1231 
mbedtls_ssl_tls13_compute_early_transform(mbedtls_ssl_context * ssl)1232 int mbedtls_ssl_tls13_compute_early_transform(mbedtls_ssl_context *ssl)
1233 {
1234     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1235     mbedtls_ssl_key_set traffic_keys;
1236     mbedtls_ssl_transform *transform_earlydata = NULL;
1237     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1238 
1239     /* Next evolution in key schedule: Establish early_data secret and
1240      * key material. */
1241     ret = ssl_tls13_generate_early_key(ssl, &traffic_keys);
1242     if (ret != 0) {
1243         MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_generate_early_key",
1244                               ret);
1245         goto cleanup;
1246     }
1247 
1248     transform_earlydata = mbedtls_calloc(1, sizeof(mbedtls_ssl_transform));
1249     if (transform_earlydata == NULL) {
1250         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1251         goto cleanup;
1252     }
1253 
1254     ret = mbedtls_ssl_tls13_populate_transform(
1255         transform_earlydata,
1256         ssl->conf->endpoint,
1257         handshake->ciphersuite_info->id,
1258         &traffic_keys,
1259         ssl);
1260     if (ret != 0) {
1261         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_populate_transform", ret);
1262         goto cleanup;
1263     }
1264     handshake->transform_earlydata = transform_earlydata;
1265 
1266 cleanup:
1267     mbedtls_platform_zeroize(&traffic_keys, sizeof(traffic_keys));
1268     if (ret != 0) {
1269         mbedtls_free(transform_earlydata);
1270     }
1271 
1272     return ret;
1273 }
1274 #endif /* MBEDTLS_SSL_EARLY_DATA */
1275 
mbedtls_ssl_tls13_key_schedule_stage_early(mbedtls_ssl_context * ssl)1276 int mbedtls_ssl_tls13_key_schedule_stage_early(mbedtls_ssl_context *ssl)
1277 {
1278     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1279     psa_algorithm_t hash_alg;
1280     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1281     unsigned char *psk = NULL;
1282     size_t psk_len = 0;
1283 
1284     if (handshake->ciphersuite_info == NULL) {
1285         MBEDTLS_SSL_DEBUG_MSG(1, ("cipher suite info not found"));
1286         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1287     }
1288 
1289     hash_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) handshake->ciphersuite_info->mac);
1290 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1291     if (mbedtls_ssl_tls13_key_exchange_mode_with_psk(ssl)) {
1292         ret = mbedtls_ssl_tls13_export_handshake_psk(ssl, &psk, &psk_len);
1293         if (ret != 0) {
1294             MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_export_handshake_psk",
1295                                   ret);
1296             return ret;
1297         }
1298     }
1299 #endif
1300 
1301     ret = mbedtls_ssl_tls13_evolve_secret(hash_alg, NULL, psk, psk_len,
1302                                           handshake->tls13_master_secrets.early);
1303 #if defined(MBEDTLS_USE_PSA_CRYPTO) && \
1304     defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1305     mbedtls_free((void *) psk);
1306 #endif
1307     if (ret != 0) {
1308         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_evolve_secret", ret);
1309         return ret;
1310     }
1311 
1312     MBEDTLS_SSL_DEBUG_BUF(4, "mbedtls_ssl_tls13_key_schedule_stage_early",
1313                           handshake->tls13_master_secrets.early,
1314                           PSA_HASH_LENGTH(hash_alg));
1315     return 0;
1316 }
1317 
1318 /**
1319  * \brief Compute TLS 1.3 handshake traffic keys.
1320  *
1321  *        ssl_tls13_generate_handshake_keys() generates keys necessary for
1322  *        protecting the handshake messages, as described in Section 7 of
1323  *        RFC 8446.
1324  *
1325  * \param ssl  The SSL context to operate on. This must be in
1326  *             key schedule stage \c Handshake, see
1327  *             ssl_tls13_key_schedule_stage_handshake().
1328  * \param traffic_keys The address at which to store the handshake traffic
1329  *                     keys. This must be writable but may be uninitialized.
1330  *
1331  * \returns    \c 0 on success.
1332  * \returns    A negative error code on failure.
1333  */
1334 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_generate_handshake_keys(mbedtls_ssl_context * ssl,mbedtls_ssl_key_set * traffic_keys)1335 static int ssl_tls13_generate_handshake_keys(mbedtls_ssl_context *ssl,
1336                                              mbedtls_ssl_key_set *traffic_keys)
1337 {
1338     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1339     mbedtls_md_type_t md_type;
1340     psa_algorithm_t hash_alg;
1341     size_t hash_len;
1342     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1343     size_t transcript_len;
1344     size_t key_len = 0;
1345     size_t iv_len = 0;
1346 
1347     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1348     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
1349         handshake->ciphersuite_info;
1350     mbedtls_ssl_tls13_handshake_secrets *tls13_hs_secrets =
1351         &handshake->tls13_hs_secrets;
1352 
1353     MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_tls13_generate_handshake_keys"));
1354 
1355     ret = ssl_tls13_get_cipher_key_info(ciphersuite_info, &key_len, &iv_len);
1356     if (ret != 0) {
1357         MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_get_cipher_key_info", ret);
1358         return ret;
1359     }
1360 
1361     md_type = (mbedtls_md_type_t) ciphersuite_info->mac;
1362 
1363     hash_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac);
1364     hash_len = PSA_HASH_LENGTH(hash_alg);
1365 
1366     ret = mbedtls_ssl_get_handshake_transcript(ssl, md_type,
1367                                                transcript,
1368                                                sizeof(transcript),
1369                                                &transcript_len);
1370     if (ret != 0) {
1371         MBEDTLS_SSL_DEBUG_RET(1,
1372                               "mbedtls_ssl_get_handshake_transcript",
1373                               ret);
1374         return ret;
1375     }
1376 
1377     ret = mbedtls_ssl_tls13_derive_handshake_secrets(
1378         hash_alg, handshake->tls13_master_secrets.handshake,
1379         transcript, transcript_len, tls13_hs_secrets);
1380     if (ret != 0) {
1381         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_derive_handshake_secrets",
1382                               ret);
1383         return ret;
1384     }
1385 
1386     MBEDTLS_SSL_DEBUG_BUF(4, "Client handshake traffic secret",
1387                           tls13_hs_secrets->client_handshake_traffic_secret,
1388                           hash_len);
1389     MBEDTLS_SSL_DEBUG_BUF(4, "Server handshake traffic secret",
1390                           tls13_hs_secrets->server_handshake_traffic_secret,
1391                           hash_len);
1392 
1393     /*
1394      * Export client handshake traffic secret
1395      */
1396     if (ssl->f_export_keys != NULL) {
1397         ssl->f_export_keys(
1398             ssl->p_export_keys,
1399             MBEDTLS_SSL_KEY_EXPORT_TLS1_3_CLIENT_HANDSHAKE_TRAFFIC_SECRET,
1400             tls13_hs_secrets->client_handshake_traffic_secret,
1401             hash_len,
1402             handshake->randbytes,
1403             handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN,
1404             MBEDTLS_SSL_TLS_PRF_NONE /* TODO: FIX! */);
1405 
1406         ssl->f_export_keys(
1407             ssl->p_export_keys,
1408             MBEDTLS_SSL_KEY_EXPORT_TLS1_3_SERVER_HANDSHAKE_TRAFFIC_SECRET,
1409             tls13_hs_secrets->server_handshake_traffic_secret,
1410             hash_len,
1411             handshake->randbytes,
1412             handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN,
1413             MBEDTLS_SSL_TLS_PRF_NONE /* TODO: FIX! */);
1414     }
1415 
1416     ret = mbedtls_ssl_tls13_make_traffic_keys(
1417         hash_alg,
1418         tls13_hs_secrets->client_handshake_traffic_secret,
1419         tls13_hs_secrets->server_handshake_traffic_secret,
1420         hash_len, key_len, iv_len, traffic_keys);
1421     if (ret != 0) {
1422         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_make_traffic_keys", ret);
1423         goto exit;
1424     }
1425 
1426     MBEDTLS_SSL_DEBUG_BUF(4, "client_handshake write_key",
1427                           traffic_keys->client_write_key,
1428                           traffic_keys->key_len);
1429 
1430     MBEDTLS_SSL_DEBUG_BUF(4, "server_handshake write_key",
1431                           traffic_keys->server_write_key,
1432                           traffic_keys->key_len);
1433 
1434     MBEDTLS_SSL_DEBUG_BUF(4, "client_handshake write_iv",
1435                           traffic_keys->client_write_iv,
1436                           traffic_keys->iv_len);
1437 
1438     MBEDTLS_SSL_DEBUG_BUF(4, "server_handshake write_iv",
1439                           traffic_keys->server_write_iv,
1440                           traffic_keys->iv_len);
1441 
1442     MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_tls13_generate_handshake_keys"));
1443 
1444 exit:
1445 
1446     return ret;
1447 }
1448 
1449 /**
1450  * \brief Transition into handshake stage of TLS 1.3 key schedule.
1451  *
1452  *        The TLS 1.3 key schedule can be viewed as a simple state machine
1453  *        with states Initial -> Early -> Handshake -> Application, and
1454  *        this function represents the Early -> Handshake transition.
1455  *
1456  *        In the handshake stage, ssl_tls13_generate_handshake_keys()
1457  *        can be used to derive the handshake traffic keys.
1458  *
1459  * \param ssl  The SSL context to operate on. This must be in key schedule
1460  *             stage \c Early.
1461  *
1462  * \returns    \c 0 on success.
1463  * \returns    A negative error code on failure.
1464  */
1465 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_key_schedule_stage_handshake(mbedtls_ssl_context * ssl)1466 static int ssl_tls13_key_schedule_stage_handshake(mbedtls_ssl_context *ssl)
1467 {
1468     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1469     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1470     psa_algorithm_t const hash_alg = mbedtls_md_psa_alg_from_type(
1471         (mbedtls_md_type_t) handshake->ciphersuite_info->mac);
1472     unsigned char *shared_secret = NULL;
1473     size_t shared_secret_len = 0;
1474 
1475 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
1476     /*
1477      * Compute ECDHE secret used to compute the handshake secret from which
1478      * client_handshake_traffic_secret and server_handshake_traffic_secret
1479      * are derived in the handshake secret derivation stage.
1480      */
1481     if (mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(ssl)) {
1482         if (mbedtls_ssl_tls13_named_group_is_ecdhe(handshake->offered_group_id) ||
1483             mbedtls_ssl_tls13_named_group_is_ffdh(handshake->offered_group_id)) {
1484 #if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
1485             psa_algorithm_t alg =
1486                 mbedtls_ssl_tls13_named_group_is_ecdhe(handshake->offered_group_id) ?
1487                 PSA_ALG_ECDH : PSA_ALG_FFDH;
1488 
1489             /* Compute ECDH shared secret. */
1490             psa_status_t status = PSA_ERROR_GENERIC_ERROR;
1491             psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
1492 
1493             status = psa_get_key_attributes(handshake->xxdh_psa_privkey,
1494                                             &key_attributes);
1495             if (status != PSA_SUCCESS) {
1496                 ret = PSA_TO_MBEDTLS_ERR(status);
1497             }
1498 
1499             shared_secret_len = PSA_BITS_TO_BYTES(
1500                 psa_get_key_bits(&key_attributes));
1501             shared_secret = mbedtls_calloc(1, shared_secret_len);
1502             if (shared_secret == NULL) {
1503                 return MBEDTLS_ERR_SSL_ALLOC_FAILED;
1504             }
1505 
1506             status = psa_raw_key_agreement(
1507                 alg, handshake->xxdh_psa_privkey,
1508                 handshake->xxdh_psa_peerkey, handshake->xxdh_psa_peerkey_len,
1509                 shared_secret, shared_secret_len, &shared_secret_len);
1510             if (status != PSA_SUCCESS) {
1511                 ret = PSA_TO_MBEDTLS_ERR(status);
1512                 MBEDTLS_SSL_DEBUG_RET(1, "psa_raw_key_agreement", ret);
1513                 goto cleanup;
1514             }
1515 
1516             status = psa_destroy_key(handshake->xxdh_psa_privkey);
1517             if (status != PSA_SUCCESS) {
1518                 ret = PSA_TO_MBEDTLS_ERR(status);
1519                 MBEDTLS_SSL_DEBUG_RET(1, "psa_destroy_key", ret);
1520                 goto cleanup;
1521             }
1522 
1523             handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
1524 #endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
1525         } else {
1526             MBEDTLS_SSL_DEBUG_MSG(1, ("Group not supported."));
1527             return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1528         }
1529     }
1530 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
1531 
1532     /*
1533      * Compute the Handshake Secret
1534      */
1535     ret = mbedtls_ssl_tls13_evolve_secret(
1536         hash_alg, handshake->tls13_master_secrets.early,
1537         shared_secret, shared_secret_len,
1538         handshake->tls13_master_secrets.handshake);
1539     if (ret != 0) {
1540         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_evolve_secret", ret);
1541         goto cleanup;
1542     }
1543 
1544     MBEDTLS_SSL_DEBUG_BUF(4, "Handshake secret",
1545                           handshake->tls13_master_secrets.handshake,
1546                           PSA_HASH_LENGTH(hash_alg));
1547 
1548 cleanup:
1549     if (shared_secret != NULL) {
1550         mbedtls_zeroize_and_free(shared_secret, shared_secret_len);
1551     }
1552 
1553     return ret;
1554 }
1555 
1556 /**
1557  * \brief Compute TLS 1.3 application traffic keys.
1558  *
1559  *        ssl_tls13_generate_application_keys() generates application traffic
1560  *        keys, since any record following a 1-RTT Finished message MUST be
1561  *        encrypted under the application traffic key.
1562  *
1563  * \param ssl  The SSL context to operate on. This must be in
1564  *             key schedule stage \c Application, see
1565  *             ssl_tls13_key_schedule_stage_application().
1566  * \param traffic_keys The address at which to store the application traffic
1567  *                     keys. This must be writable but may be uninitialized.
1568  *
1569  * \returns    \c 0 on success.
1570  * \returns    A negative error code on failure.
1571  */
1572 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_tls13_generate_application_keys(mbedtls_ssl_context * ssl,mbedtls_ssl_key_set * traffic_keys)1573 static int ssl_tls13_generate_application_keys(
1574     mbedtls_ssl_context *ssl,
1575     mbedtls_ssl_key_set *traffic_keys)
1576 {
1577     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1578     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1579 
1580     /* Address at which to store the application secrets */
1581     mbedtls_ssl_tls13_application_secrets * const app_secrets =
1582         &ssl->session_negotiate->app_secrets;
1583 
1584     /* Holding the transcript up to and including the ServerFinished */
1585     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1586     size_t transcript_len;
1587 
1588     /* Variables relating to the hash for the chosen ciphersuite. */
1589     mbedtls_md_type_t md_type;
1590 
1591     psa_algorithm_t hash_alg;
1592     size_t hash_len;
1593 
1594     /* Variables relating to the cipher for the chosen ciphersuite. */
1595     size_t key_len = 0, iv_len = 0;
1596 
1597     MBEDTLS_SSL_DEBUG_MSG(2, ("=> derive application traffic keys"));
1598 
1599     /* Extract basic information about hash and ciphersuite */
1600 
1601     ret = ssl_tls13_get_cipher_key_info(handshake->ciphersuite_info,
1602                                         &key_len, &iv_len);
1603     if (ret != 0) {
1604         MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_get_cipher_key_info", ret);
1605         goto cleanup;
1606     }
1607 
1608     md_type = (mbedtls_md_type_t) handshake->ciphersuite_info->mac;
1609 
1610     hash_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) handshake->ciphersuite_info->mac);
1611     hash_len = PSA_HASH_LENGTH(hash_alg);
1612 
1613     /* Compute current handshake transcript. It's the caller's responsibility
1614      * to call this at the right time, that is, after the ServerFinished. */
1615 
1616     ret = mbedtls_ssl_get_handshake_transcript(ssl, md_type,
1617                                                transcript, sizeof(transcript),
1618                                                &transcript_len);
1619     if (ret != 0) {
1620         goto cleanup;
1621     }
1622 
1623     /* Compute application secrets from master secret and transcript hash. */
1624 
1625     ret = mbedtls_ssl_tls13_derive_application_secrets(
1626         hash_alg, handshake->tls13_master_secrets.app,
1627         transcript, transcript_len, app_secrets);
1628     if (ret != 0) {
1629         MBEDTLS_SSL_DEBUG_RET(
1630             1, "mbedtls_ssl_tls13_derive_application_secrets", ret);
1631         goto cleanup;
1632     }
1633 
1634     /* Derive first epoch of IV + Key for application traffic. */
1635 
1636     ret = mbedtls_ssl_tls13_make_traffic_keys(
1637         hash_alg,
1638         app_secrets->client_application_traffic_secret_N,
1639         app_secrets->server_application_traffic_secret_N,
1640         hash_len, key_len, iv_len, traffic_keys);
1641     if (ret != 0) {
1642         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_make_traffic_keys", ret);
1643         goto cleanup;
1644     }
1645 
1646     MBEDTLS_SSL_DEBUG_BUF(4, "Client application traffic secret",
1647                           app_secrets->client_application_traffic_secret_N,
1648                           hash_len);
1649 
1650     MBEDTLS_SSL_DEBUG_BUF(4, "Server application traffic secret",
1651                           app_secrets->server_application_traffic_secret_N,
1652                           hash_len);
1653 
1654     /*
1655      * Export client/server application traffic secret 0
1656      */
1657     if (ssl->f_export_keys != NULL) {
1658         ssl->f_export_keys(
1659             ssl->p_export_keys,
1660             MBEDTLS_SSL_KEY_EXPORT_TLS1_3_CLIENT_APPLICATION_TRAFFIC_SECRET,
1661             app_secrets->client_application_traffic_secret_N, hash_len,
1662             handshake->randbytes,
1663             handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN,
1664             MBEDTLS_SSL_TLS_PRF_NONE /* TODO: this should be replaced by
1665                                         a new constant for TLS 1.3! */);
1666 
1667         ssl->f_export_keys(
1668             ssl->p_export_keys,
1669             MBEDTLS_SSL_KEY_EXPORT_TLS1_3_SERVER_APPLICATION_TRAFFIC_SECRET,
1670             app_secrets->server_application_traffic_secret_N, hash_len,
1671             handshake->randbytes,
1672             handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN,
1673             MBEDTLS_SSL_TLS_PRF_NONE /* TODO: this should be replaced by
1674                                         a new constant for TLS 1.3! */);
1675     }
1676 
1677     MBEDTLS_SSL_DEBUG_BUF(4, "client application_write_key:",
1678                           traffic_keys->client_write_key, key_len);
1679     MBEDTLS_SSL_DEBUG_BUF(4, "server application write key",
1680                           traffic_keys->server_write_key, key_len);
1681     MBEDTLS_SSL_DEBUG_BUF(4, "client application write IV",
1682                           traffic_keys->client_write_iv, iv_len);
1683     MBEDTLS_SSL_DEBUG_BUF(4, "server application write IV",
1684                           traffic_keys->server_write_iv, iv_len);
1685 
1686     MBEDTLS_SSL_DEBUG_MSG(2, ("<= derive application traffic keys"));
1687 
1688 cleanup:
1689     /* randbytes is not used again */
1690     mbedtls_platform_zeroize(ssl->handshake->randbytes,
1691                              sizeof(ssl->handshake->randbytes));
1692 
1693     mbedtls_platform_zeroize(transcript, sizeof(transcript));
1694     return ret;
1695 }
1696 
mbedtls_ssl_tls13_compute_handshake_transform(mbedtls_ssl_context * ssl)1697 int mbedtls_ssl_tls13_compute_handshake_transform(mbedtls_ssl_context *ssl)
1698 {
1699     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1700     mbedtls_ssl_key_set traffic_keys;
1701     mbedtls_ssl_transform *transform_handshake = NULL;
1702     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1703 
1704     /* Compute handshake secret */
1705     ret = ssl_tls13_key_schedule_stage_handshake(ssl);
1706     if (ret != 0) {
1707         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_derive_master_secret", ret);
1708         goto cleanup;
1709     }
1710 
1711     /* Next evolution in key schedule: Establish handshake secret and
1712      * key material. */
1713     ret = ssl_tls13_generate_handshake_keys(ssl, &traffic_keys);
1714     if (ret != 0) {
1715         MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_generate_handshake_keys",
1716                               ret);
1717         goto cleanup;
1718     }
1719 
1720     transform_handshake = mbedtls_calloc(1, sizeof(mbedtls_ssl_transform));
1721     if (transform_handshake == NULL) {
1722         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1723         goto cleanup;
1724     }
1725 
1726     ret = mbedtls_ssl_tls13_populate_transform(
1727         transform_handshake,
1728         ssl->conf->endpoint,
1729         handshake->ciphersuite_info->id,
1730         &traffic_keys,
1731         ssl);
1732     if (ret != 0) {
1733         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_populate_transform", ret);
1734         goto cleanup;
1735     }
1736     handshake->transform_handshake = transform_handshake;
1737 
1738 cleanup:
1739     mbedtls_platform_zeroize(&traffic_keys, sizeof(traffic_keys));
1740     if (ret != 0) {
1741         mbedtls_free(transform_handshake);
1742     }
1743 
1744     return ret;
1745 }
1746 
mbedtls_ssl_tls13_compute_resumption_master_secret(mbedtls_ssl_context * ssl)1747 int mbedtls_ssl_tls13_compute_resumption_master_secret(mbedtls_ssl_context *ssl)
1748 {
1749     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1750     mbedtls_md_type_t md_type;
1751     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1752     unsigned char transcript[MBEDTLS_TLS1_3_MD_MAX_SIZE];
1753     size_t transcript_len;
1754 
1755     MBEDTLS_SSL_DEBUG_MSG(
1756         2, ("=> mbedtls_ssl_tls13_compute_resumption_master_secret"));
1757 
1758     md_type = (mbedtls_md_type_t) handshake->ciphersuite_info->mac;
1759 
1760     ret = mbedtls_ssl_get_handshake_transcript(ssl, md_type,
1761                                                transcript, sizeof(transcript),
1762                                                &transcript_len);
1763     if (ret != 0) {
1764         return ret;
1765     }
1766 
1767     ret = mbedtls_ssl_tls13_derive_resumption_master_secret(
1768         mbedtls_md_psa_alg_from_type(md_type),
1769         handshake->tls13_master_secrets.app,
1770         transcript, transcript_len,
1771         &ssl->session_negotiate->app_secrets);
1772     if (ret != 0) {
1773         return ret;
1774     }
1775 
1776     /* Erase master secrets */
1777     mbedtls_platform_zeroize(&handshake->tls13_master_secrets,
1778                              sizeof(handshake->tls13_master_secrets));
1779 
1780     MBEDTLS_SSL_DEBUG_BUF(
1781         4, "Resumption master secret",
1782         ssl->session_negotiate->app_secrets.resumption_master_secret,
1783         PSA_HASH_LENGTH(mbedtls_md_psa_alg_from_type(md_type)));
1784 
1785     MBEDTLS_SSL_DEBUG_MSG(
1786         2, ("<= mbedtls_ssl_tls13_compute_resumption_master_secret"));
1787     return 0;
1788 }
1789 
mbedtls_ssl_tls13_compute_application_transform(mbedtls_ssl_context * ssl)1790 int mbedtls_ssl_tls13_compute_application_transform(mbedtls_ssl_context *ssl)
1791 {
1792     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1793     mbedtls_ssl_key_set traffic_keys;
1794     mbedtls_ssl_transform *transform_application = NULL;
1795 
1796     ret = ssl_tls13_key_schedule_stage_application(ssl);
1797     if (ret != 0) {
1798         MBEDTLS_SSL_DEBUG_RET(1,
1799                               "ssl_tls13_key_schedule_stage_application", ret);
1800         goto cleanup;
1801     }
1802 
1803     ret = ssl_tls13_generate_application_keys(ssl, &traffic_keys);
1804     if (ret != 0) {
1805         MBEDTLS_SSL_DEBUG_RET(1,
1806                               "ssl_tls13_generate_application_keys", ret);
1807         goto cleanup;
1808     }
1809 
1810     transform_application =
1811         mbedtls_calloc(1, sizeof(mbedtls_ssl_transform));
1812     if (transform_application == NULL) {
1813         ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
1814         goto cleanup;
1815     }
1816 
1817     ret = mbedtls_ssl_tls13_populate_transform(
1818         transform_application,
1819         ssl->conf->endpoint,
1820         ssl->handshake->ciphersuite_info->id,
1821         &traffic_keys,
1822         ssl);
1823     if (ret != 0) {
1824         MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_tls13_populate_transform", ret);
1825         goto cleanup;
1826     }
1827 
1828     ssl->transform_application = transform_application;
1829 
1830 cleanup:
1831 
1832     mbedtls_platform_zeroize(&traffic_keys, sizeof(traffic_keys));
1833     if (ret != 0) {
1834         mbedtls_free(transform_application);
1835     }
1836     return ret;
1837 }
1838 
1839 #if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
mbedtls_ssl_tls13_export_handshake_psk(mbedtls_ssl_context * ssl,unsigned char ** psk,size_t * psk_len)1840 int mbedtls_ssl_tls13_export_handshake_psk(mbedtls_ssl_context *ssl,
1841                                            unsigned char **psk,
1842                                            size_t *psk_len)
1843 {
1844 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1845     psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
1846     psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1847 
1848     *psk_len = 0;
1849     *psk = NULL;
1850 
1851     if (mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque)) {
1852         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1853     }
1854 
1855     status = psa_get_key_attributes(ssl->handshake->psk_opaque, &key_attributes);
1856     if (status != PSA_SUCCESS) {
1857         return PSA_TO_MBEDTLS_ERR(status);
1858     }
1859 
1860     *psk_len = PSA_BITS_TO_BYTES(psa_get_key_bits(&key_attributes));
1861     *psk = mbedtls_calloc(1, *psk_len);
1862     if (*psk == NULL) {
1863         return MBEDTLS_ERR_SSL_ALLOC_FAILED;
1864     }
1865 
1866     status = psa_export_key(ssl->handshake->psk_opaque,
1867                             (uint8_t *) *psk, *psk_len, psk_len);
1868     if (status != PSA_SUCCESS) {
1869         mbedtls_free((void *) *psk);
1870         *psk = NULL;
1871         return PSA_TO_MBEDTLS_ERR(status);
1872     }
1873     return 0;
1874 #else
1875     *psk = ssl->handshake->psk;
1876     *psk_len = ssl->handshake->psk_len;
1877     if (*psk == NULL) {
1878         return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1879     }
1880     return 0;
1881 #endif /* !MBEDTLS_USE_PSA_CRYPTO */
1882 }
1883 #endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1884 
1885 #endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
1886