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