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