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