1 /*
2  *  TLS client-side functions
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_CLI_C) && defined(MBEDTLS_SSL_PROTO_TLS1_2)
23 
24 #include "mbedtls/platform.h"
25 
26 #include "mbedtls/ssl.h"
27 #include "ssl_client.h"
28 #include "ssl_misc.h"
29 #include "mbedtls/debug.h"
30 #include "mbedtls/error.h"
31 #include "mbedtls/constant_time.h"
32 
33 #if defined(MBEDTLS_USE_PSA_CRYPTO)
34 #include "mbedtls/psa_util.h"
35 #include "psa/crypto.h"
36 #endif /* MBEDTLS_USE_PSA_CRYPTO */
37 
38 #include <string.h>
39 
40 #include <stdint.h>
41 
42 #if defined(MBEDTLS_HAVE_TIME)
43 #include "mbedtls/platform_time.h"
44 #endif
45 
46 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
47 #include "mbedtls/platform_util.h"
48 #endif
49 
50 #include "hash_info.h"
51 
52 #if defined(MBEDTLS_SSL_RENEGOTIATION)
53 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_renegotiation_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)54 static int ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
55                                         unsigned char *buf,
56                                         const unsigned char *end,
57                                         size_t *olen )
58 {
59     unsigned char *p = buf;
60 
61     *olen = 0;
62 
63     /* We're always including a TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
64      * initial ClientHello, in which case also adding the renegotiation
65      * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
66     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
67         return( 0 );
68 
69     MBEDTLS_SSL_DEBUG_MSG( 3,
70         ( "client hello, adding renegotiation extension" ) );
71 
72     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 + ssl->verify_data_len );
73 
74     /*
75      * Secure renegotiation
76      */
77     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO, p, 0 );
78     p += 2;
79 
80     *p++ = 0x00;
81     *p++ = MBEDTLS_BYTE_0( ssl->verify_data_len + 1 );
82     *p++ = MBEDTLS_BYTE_0( ssl->verify_data_len );
83 
84     memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
85 
86     *olen = 5 + ssl->verify_data_len;
87 
88     return( 0 );
89 }
90 #endif /* MBEDTLS_SSL_RENEGOTIATION */
91 
92 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
93     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
94 
95 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_supported_point_formats_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)96 static int ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
97                                                   unsigned char *buf,
98                                                   const unsigned char *end,
99                                                   size_t *olen )
100 {
101     unsigned char *p = buf;
102     (void) ssl; /* ssl used for debugging only */
103 
104     *olen = 0;
105 
106     MBEDTLS_SSL_DEBUG_MSG( 3,
107         ( "client hello, adding supported_point_formats extension" ) );
108     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 );
109 
110     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS, p, 0 );
111     p += 2;
112 
113     *p++ = 0x00;
114     *p++ = 2;
115 
116     *p++ = 1;
117     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
118 
119     *olen = 6;
120 
121     return( 0 );
122 }
123 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
124           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
125 
126 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
127 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)128 static int ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
129                                        unsigned char *buf,
130                                        const unsigned char *end,
131                                        size_t *olen )
132 {
133     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
134     unsigned char *p = buf;
135     size_t kkpp_len = 0;
136 
137     *olen = 0;
138 
139     /* Skip costly extension if we can't use EC J-PAKE anyway */
140 #if defined(MBEDTLS_USE_PSA_CRYPTO)
141     if( ssl->handshake->psa_pake_ctx_is_ok != 1 )
142         return( 0 );
143 #else
144     if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
145         return( 0 );
146 #endif /* MBEDTLS_USE_PSA_CRYPTO */
147 
148     MBEDTLS_SSL_DEBUG_MSG( 3,
149         ( "client hello, adding ecjpake_kkpp extension" ) );
150 
151     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 );
152 
153     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0 );
154     p += 2;
155 
156     /*
157      * We may need to send ClientHello multiple times for Hello verification.
158      * We don't want to compute fresh values every time (both for performance
159      * and consistency reasons), so cache the extension content.
160      */
161     if( ssl->handshake->ecjpake_cache == NULL ||
162         ssl->handshake->ecjpake_cache_len == 0 )
163     {
164         MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
165 
166 #if defined(MBEDTLS_USE_PSA_CRYPTO)
167         ret = mbedtls_psa_ecjpake_write_round(&ssl->handshake->psa_pake_ctx,
168                                                 p + 2, end - p - 2, &kkpp_len,
169                                                 MBEDTLS_ECJPAKE_ROUND_ONE );
170         if ( ret != 0 )
171         {
172             psa_destroy_key( ssl->handshake->psa_pake_password );
173             psa_pake_abort( &ssl->handshake->psa_pake_ctx );
174             MBEDTLS_SSL_DEBUG_RET( 1 , "psa_pake_output", ret );
175             return( ret );
176         }
177 #else
178         ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
179                                                p + 2, end - p - 2, &kkpp_len,
180                                                ssl->conf->f_rng, ssl->conf->p_rng );
181         if( ret != 0 )
182         {
183             MBEDTLS_SSL_DEBUG_RET( 1 ,
184                 "mbedtls_ecjpake_write_round_one", ret );
185             return( ret );
186         }
187 #endif /* MBEDTLS_USE_PSA_CRYPTO */
188 
189         ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
190         if( ssl->handshake->ecjpake_cache == NULL )
191         {
192             MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
193             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
194         }
195 
196         memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
197         ssl->handshake->ecjpake_cache_len = kkpp_len;
198     }
199     else
200     {
201         MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
202 
203         kkpp_len = ssl->handshake->ecjpake_cache_len;
204         MBEDTLS_SSL_CHK_BUF_PTR( p + 2, end, kkpp_len );
205 
206         memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
207     }
208 
209     MBEDTLS_PUT_UINT16_BE( kkpp_len, p, 0 );
210     p += 2;
211 
212     *olen = kkpp_len + 4;
213 
214     return( 0 );
215 }
216 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
217 
218 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
219 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_cid_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)220 static int ssl_write_cid_ext( mbedtls_ssl_context *ssl,
221                               unsigned char *buf,
222                               const unsigned char *end,
223                               size_t *olen )
224 {
225     unsigned char *p = buf;
226     size_t ext_len;
227 
228     /*
229      *   struct {
230      *      opaque cid<0..2^8-1>;
231      *   } ConnectionId;
232     */
233 
234     *olen = 0;
235     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
236         ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED )
237     {
238         return( 0 );
239     }
240     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding CID extension" ) );
241 
242     /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX
243      * which is at most 255, so the increment cannot overflow. */
244     MBEDTLS_SSL_CHK_BUF_PTR( p, end, (unsigned)( ssl->own_cid_len + 5 ) );
245 
246     /* Add extension ID + size */
247     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_CID, p, 0 );
248     p += 2;
249     ext_len = (size_t) ssl->own_cid_len + 1;
250     MBEDTLS_PUT_UINT16_BE( ext_len, p, 0 );
251     p += 2;
252 
253     *p++ = (uint8_t) ssl->own_cid_len;
254     memcpy( p, ssl->own_cid, ssl->own_cid_len );
255 
256     *olen = ssl->own_cid_len + 5;
257 
258     return( 0 );
259 }
260 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
261 
262 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
263 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_max_fragment_length_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)264 static int ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
265                                               unsigned char *buf,
266                                               const unsigned char *end,
267                                               size_t *olen )
268 {
269     unsigned char *p = buf;
270 
271     *olen = 0;
272 
273     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE )
274         return( 0 );
275 
276     MBEDTLS_SSL_DEBUG_MSG( 3,
277         ( "client hello, adding max_fragment_length extension" ) );
278 
279     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 );
280 
281     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH, p, 0 );
282     p += 2;
283 
284     *p++ = 0x00;
285     *p++ = 1;
286 
287     *p++ = ssl->conf->mfl_code;
288 
289     *olen = 5;
290 
291     return( 0 );
292 }
293 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
294 
295 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
296 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)297 static int ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
298                                            unsigned char *buf,
299                                            const unsigned char *end,
300                                            size_t *olen )
301 {
302     unsigned char *p = buf;
303 
304     *olen = 0;
305 
306     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED )
307         return( 0 );
308 
309     MBEDTLS_SSL_DEBUG_MSG( 3,
310         ( "client hello, adding encrypt_then_mac extension" ) );
311 
312     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 );
313 
314     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC, p, 0 );
315     p += 2;
316 
317     *p++ = 0x00;
318     *p++ = 0x00;
319 
320     *olen = 4;
321 
322     return( 0 );
323 }
324 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
325 
326 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
327 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_extended_ms_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)328 static int ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
329                                       unsigned char *buf,
330                                       const unsigned char *end,
331                                       size_t *olen )
332 {
333     unsigned char *p = buf;
334 
335     *olen = 0;
336 
337     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED )
338         return( 0 );
339 
340     MBEDTLS_SSL_DEBUG_MSG( 3,
341         ( "client hello, adding extended_master_secret extension" ) );
342 
343     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 );
344 
345     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET, p, 0 );
346     p += 2;
347 
348     *p++ = 0x00;
349     *p++ = 0x00;
350 
351     *olen = 4;
352 
353     return( 0 );
354 }
355 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
356 
357 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
358 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_session_ticket_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)359 static int ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
360                                          unsigned char *buf,
361                                          const unsigned char *end,
362                                          size_t *olen )
363 {
364     unsigned char *p = buf;
365     size_t tlen = ssl->session_negotiate->ticket_len;
366 
367     *olen = 0;
368 
369     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
370         return( 0 );
371 
372     MBEDTLS_SSL_DEBUG_MSG( 3,
373         ( "client hello, adding session ticket extension" ) );
374 
375     /* The addition is safe here since the ticket length is 16 bit. */
376     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 + tlen );
377 
378     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_SESSION_TICKET, p, 0 );
379     p += 2;
380 
381     MBEDTLS_PUT_UINT16_BE( tlen, p, 0 );
382     p += 2;
383 
384     *olen = 4;
385 
386     if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
387         return( 0 );
388 
389     MBEDTLS_SSL_DEBUG_MSG( 3,
390         ( "sending session ticket of length %" MBEDTLS_PRINTF_SIZET, tlen ) );
391 
392     memcpy( p, ssl->session_negotiate->ticket, tlen );
393 
394     *olen += tlen;
395 
396     return( 0 );
397 }
398 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
399 
400 #if defined(MBEDTLS_SSL_DTLS_SRTP)
401 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_use_srtp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)402 static int ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl,
403                                    unsigned char *buf,
404                                    const unsigned char *end,
405                                    size_t *olen )
406 {
407     unsigned char *p = buf;
408     size_t protection_profiles_index = 0, ext_len = 0;
409     uint16_t mki_len = 0, profile_value = 0;
410 
411     *olen = 0;
412 
413     if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
414         ( ssl->conf->dtls_srtp_profile_list == NULL ) ||
415         ( ssl->conf->dtls_srtp_profile_list_len == 0 ) )
416     {
417         return( 0 );
418     }
419 
420     /* RFC 5764 section 4.1.1
421      * uint8 SRTPProtectionProfile[2];
422      *
423      * struct {
424      *   SRTPProtectionProfiles SRTPProtectionProfiles;
425      *   opaque srtp_mki<0..255>;
426      * } UseSRTPData;
427      * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
428      */
429     if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED )
430     {
431         mki_len = ssl->dtls_srtp_info.mki_len;
432     }
433     /* Extension length = 2 bytes for profiles length,
434      *                    ssl->conf->dtls_srtp_profile_list_len * 2 (each profile is 2 bytes length ),
435      *                    1 byte for srtp_mki vector length and the mki_len value
436      */
437     ext_len = 2 + 2 * ( ssl->conf->dtls_srtp_profile_list_len ) + 1 + mki_len;
438 
439     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding use_srtp extension" ) );
440 
441     /* Check there is room in the buffer for the extension + 4 bytes
442      * - the extension tag (2 bytes)
443      * - the extension length (2 bytes)
444      */
445     MBEDTLS_SSL_CHK_BUF_PTR( p, end, ext_len + 4 );
446 
447     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_USE_SRTP, p, 0 );
448     p += 2;
449 
450     MBEDTLS_PUT_UINT16_BE( ext_len, p, 0 );
451     p += 2;
452 
453     /* protection profile length: 2*(ssl->conf->dtls_srtp_profile_list_len) */
454     /* micro-optimization:
455      * the list size is limited to MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH
456      * which is lower than 127, so the upper byte of the length is always 0
457      * For the documentation, the more generic code is left in comments
458      * *p++ = (unsigned char)( ( ( 2 * ssl->conf->dtls_srtp_profile_list_len )
459      *                        >> 8 ) & 0xFF );
460      */
461     *p++ = 0;
462     *p++ = MBEDTLS_BYTE_0( 2 * ssl->conf->dtls_srtp_profile_list_len );
463 
464     for( protection_profiles_index=0;
465          protection_profiles_index < ssl->conf->dtls_srtp_profile_list_len;
466          protection_profiles_index++ )
467     {
468         profile_value = mbedtls_ssl_check_srtp_profile_value
469                 ( ssl->conf->dtls_srtp_profile_list[protection_profiles_index] );
470         if( profile_value != MBEDTLS_TLS_SRTP_UNSET )
471         {
472             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_write_use_srtp_ext, add profile: %04x",
473                                         profile_value ) );
474             MBEDTLS_PUT_UINT16_BE( profile_value, p, 0 );
475             p += 2;
476         }
477         else
478         {
479             /*
480              * Note: we shall never arrive here as protection profiles
481              * is checked by mbedtls_ssl_conf_dtls_srtp_protection_profiles function
482              */
483             MBEDTLS_SSL_DEBUG_MSG( 3,
484                     ( "client hello, "
485                       "illegal DTLS-SRTP protection profile %d",
486                       ssl->conf->dtls_srtp_profile_list[protection_profiles_index]
487                     ) );
488             return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED );
489         }
490     }
491 
492     *p++ = mki_len & 0xFF;
493 
494     if( mki_len != 0 )
495     {
496         memcpy( p, ssl->dtls_srtp_info.mki_value, mki_len );
497         /*
498          * Increment p to point to the current position.
499          */
500         p += mki_len;
501         MBEDTLS_SSL_DEBUG_BUF( 3, "sending mki",  ssl->dtls_srtp_info.mki_value,
502                                ssl->dtls_srtp_info.mki_len );
503     }
504 
505     /*
506      * total extension length: extension type (2 bytes)
507      *                         + extension length (2 bytes)
508      *                         + protection profile length (2 bytes)
509      *                         + 2 * number of protection profiles
510      *                         + srtp_mki vector length(1 byte)
511      *                         + mki value
512      */
513     *olen = p - buf;
514 
515     return( 0 );
516 }
517 #endif /* MBEDTLS_SSL_DTLS_SRTP */
518 
mbedtls_ssl_tls12_write_client_hello_exts(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,int uses_ec,size_t * out_len)519 int mbedtls_ssl_tls12_write_client_hello_exts( mbedtls_ssl_context *ssl,
520                                                unsigned char *buf,
521                                                const unsigned char *end,
522                                                int uses_ec,
523                                                size_t *out_len )
524 {
525     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
526     unsigned char *p = buf;
527     size_t ext_len = 0;
528 
529     (void) ssl;
530     (void) end;
531     (void) uses_ec;
532     (void) ret;
533     (void) ext_len;
534 
535     *out_len = 0;
536 
537     /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
538      * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
539 #if defined(MBEDTLS_SSL_RENEGOTIATION)
540     if( ( ret = ssl_write_renegotiation_ext( ssl, p, end, &ext_len ) ) != 0 )
541     {
542         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_renegotiation_ext", ret );
543         return( ret );
544     }
545     p += ext_len;
546 #endif
547 
548 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
549     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
550     if( uses_ec )
551     {
552         if( ( ret = ssl_write_supported_point_formats_ext( ssl, p, end,
553                                                            &ext_len ) ) != 0 )
554         {
555             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_point_formats_ext", ret );
556             return( ret );
557         }
558         p += ext_len;
559     }
560 #endif
561 
562 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
563     if( ( ret = ssl_write_ecjpake_kkpp_ext( ssl, p, end, &ext_len ) ) != 0 )
564     {
565         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_ecjpake_kkpp_ext", ret );
566         return( ret );
567     }
568     p += ext_len;
569 #endif
570 
571 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
572     if( ( ret = ssl_write_cid_ext( ssl, p, end, &ext_len ) ) != 0 )
573     {
574         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_cid_ext", ret );
575         return( ret );
576     }
577     p += ext_len;
578 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
579 
580 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
581     if( ( ret = ssl_write_max_fragment_length_ext( ssl, p, end,
582                                                    &ext_len ) ) != 0 )
583     {
584         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_max_fragment_length_ext", ret );
585         return( ret );
586     }
587     p += ext_len;
588 #endif
589 
590 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
591     if( ( ret = ssl_write_encrypt_then_mac_ext( ssl, p, end, &ext_len ) ) != 0 )
592     {
593         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_encrypt_then_mac_ext", ret );
594         return( ret );
595     }
596     p += ext_len;
597 #endif
598 
599 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
600     if( ( ret = ssl_write_extended_ms_ext( ssl, p, end, &ext_len ) ) != 0 )
601     {
602         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_extended_ms_ext", ret );
603         return( ret );
604     }
605     p += ext_len;
606 #endif
607 
608 #if defined(MBEDTLS_SSL_DTLS_SRTP)
609     if( ( ret = ssl_write_use_srtp_ext( ssl, p, end, &ext_len ) ) != 0 )
610     {
611         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_use_srtp_ext", ret );
612         return( ret );
613     }
614     p += ext_len;
615 #endif
616 
617 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
618     if( ( ret = ssl_write_session_ticket_ext( ssl, p, end, &ext_len ) ) != 0 )
619     {
620         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_session_ticket_ext", ret );
621         return( ret );
622     }
623     p += ext_len;
624 #endif
625 
626     *out_len = p - buf;
627 
628     return( 0 );
629 }
630 
631 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_renegotiation_info(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)632 static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
633                                          const unsigned char *buf,
634                                          size_t len )
635 {
636 #if defined(MBEDTLS_SSL_RENEGOTIATION)
637     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
638     {
639         /* Check verify-data in constant-time. The length OTOH is no secret */
640         if( len    != 1 + ssl->verify_data_len * 2 ||
641             buf[0] !=     ssl->verify_data_len * 2 ||
642             mbedtls_ct_memcmp( buf + 1,
643                           ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
644             mbedtls_ct_memcmp( buf + 1 + ssl->verify_data_len,
645                           ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
646         {
647             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
648             mbedtls_ssl_send_alert_message(
649                 ssl,
650                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
651                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
652             return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
653         }
654     }
655     else
656 #endif /* MBEDTLS_SSL_RENEGOTIATION */
657     {
658         if( len != 1 || buf[0] != 0x00 )
659         {
660             MBEDTLS_SSL_DEBUG_MSG( 1,
661                 ( "non-zero length renegotiation info" ) );
662             mbedtls_ssl_send_alert_message(
663                 ssl,
664                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
665                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
666             return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
667         }
668 
669         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
670     }
671 
672     return( 0 );
673 }
674 
675 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
676 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_max_fragment_length_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)677 static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
678                                               const unsigned char *buf,
679                                               size_t len )
680 {
681     /*
682      * server should use the extension only if we did,
683      * and if so the server's value should match ours (and len is always 1)
684      */
685     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
686         len != 1 ||
687         buf[0] != ssl->conf->mfl_code )
688     {
689         MBEDTLS_SSL_DEBUG_MSG( 1,
690             ( "non-matching max fragment length extension" ) );
691         mbedtls_ssl_send_alert_message(
692             ssl,
693             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
694             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
695         return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
696     }
697 
698     return( 0 );
699 }
700 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
701 
702 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
703 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_cid_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)704 static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl,
705                               const unsigned char *buf,
706                               size_t len )
707 {
708     size_t peer_cid_len;
709 
710     if( /* CID extension only makes sense in DTLS */
711         ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
712         /* The server must only send the CID extension if we have offered it. */
713         ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED )
714     {
715         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension unexpected" ) );
716         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
717                                         MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT );
718         return( MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
719     }
720 
721     if( len == 0 )
722     {
723         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) );
724         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
725                                      MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
726         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
727     }
728 
729     peer_cid_len = *buf++;
730     len--;
731 
732     if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX )
733     {
734         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) );
735         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
736                                      MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
737         return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
738     }
739 
740     if( len != peer_cid_len )
741     {
742         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) );
743         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
744                                      MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
745         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
746     }
747 
748     ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
749     ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
750     memcpy( ssl->handshake->peer_cid, buf, peer_cid_len );
751 
752     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) );
753     MBEDTLS_SSL_DEBUG_BUF( 3, "Server CID", buf, peer_cid_len );
754 
755     return( 0 );
756 }
757 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
758 
759 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
760 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)761 static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
762                                          const unsigned char *buf,
763                                          size_t len )
764 {
765     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
766         len != 0 )
767     {
768         MBEDTLS_SSL_DEBUG_MSG( 1,
769             ( "non-matching encrypt-then-MAC extension" ) );
770         mbedtls_ssl_send_alert_message(
771             ssl,
772             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
773             MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT );
774         return( MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
775     }
776 
777     ((void) buf);
778 
779     ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
780 
781     return( 0 );
782 }
783 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
784 
785 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
786 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_extended_ms_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)787 static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
788                                          const unsigned char *buf,
789                                          size_t len )
790 {
791     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
792         len != 0 )
793     {
794         MBEDTLS_SSL_DEBUG_MSG( 1,
795             ( "non-matching extended master secret extension" ) );
796         mbedtls_ssl_send_alert_message(
797             ssl,
798             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
799             MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT );
800         return( MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
801     }
802 
803     ((void) buf);
804 
805     ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
806 
807     return( 0 );
808 }
809 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
810 
811 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
812 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_session_ticket_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)813 static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
814                                          const unsigned char *buf,
815                                          size_t len )
816 {
817     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
818         len != 0 )
819     {
820         MBEDTLS_SSL_DEBUG_MSG( 1,
821             ( "non-matching session ticket extension" ) );
822         mbedtls_ssl_send_alert_message(
823             ssl,
824             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
825             MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT );
826         return( MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
827     }
828 
829     ((void) buf);
830 
831     ssl->handshake->new_session_ticket = 1;
832 
833     return( 0 );
834 }
835 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
836 
837 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
838     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
839 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_supported_point_formats_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)840 static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
841                                                   const unsigned char *buf,
842                                                   size_t len )
843 {
844     size_t list_size;
845     const unsigned char *p;
846 
847     if( len == 0 || (size_t)( buf[0] + 1 ) != len )
848     {
849         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
850         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
851                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
852         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
853     }
854     list_size = buf[0];
855 
856     p = buf + 1;
857     while( list_size > 0 )
858     {
859         if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
860             p[0] == MBEDTLS_ECP_PF_COMPRESSED )
861         {
862 #if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
863     ( defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) )
864             ssl->handshake->ecdh_ctx.point_format = p[0];
865 #endif /* !MBEDTLS_USE_PSA_CRYPTO &&
866           ( MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ) */
867 #if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
868     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
869             mbedtls_ecjpake_set_point_format( &ssl->handshake->ecjpake_ctx,
870                                               p[0] );
871 #endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
872             MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
873             return( 0 );
874         }
875 
876         list_size--;
877         p++;
878     }
879 
880     MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
881     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
882                                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
883     return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
884 }
885 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
886           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
887 
888 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
889 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_ecjpake_kkpp(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)890 static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
891                                    const unsigned char *buf,
892                                    size_t len )
893 {
894     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
895 
896     if( ssl->handshake->ciphersuite_info->key_exchange !=
897         MBEDTLS_KEY_EXCHANGE_ECJPAKE )
898     {
899         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
900         return( 0 );
901     }
902 
903     /* If we got here, we no longer need our cached extension */
904     mbedtls_free( ssl->handshake->ecjpake_cache );
905     ssl->handshake->ecjpake_cache = NULL;
906     ssl->handshake->ecjpake_cache_len = 0;
907 
908 #if defined(MBEDTLS_USE_PSA_CRYPTO)
909     if( ( ret = mbedtls_psa_ecjpake_read_round(
910                             &ssl->handshake->psa_pake_ctx, buf, len,
911                             MBEDTLS_ECJPAKE_ROUND_ONE ) ) != 0 )
912     {
913         psa_destroy_key( ssl->handshake->psa_pake_password );
914         psa_pake_abort( &ssl->handshake->psa_pake_ctx );
915 
916         MBEDTLS_SSL_DEBUG_RET( 1, "psa_pake_input round one", ret );
917         mbedtls_ssl_send_alert_message(
918                 ssl,
919                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
920                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
921         return( ret );
922     }
923 
924     return( 0 );
925 #else
926     if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
927                                                 buf, len ) ) != 0 )
928     {
929         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
930         mbedtls_ssl_send_alert_message(
931             ssl,
932             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
933             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
934         return( ret );
935     }
936 
937     return( 0 );
938 #endif /* MBEDTLS_USE_PSA_CRYPTO */
939 }
940 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
941 
942 #if defined(MBEDTLS_SSL_ALPN)
943 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_alpn_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)944 static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
945                                const unsigned char *buf, size_t len )
946 {
947     size_t list_len, name_len;
948     const char **p;
949 
950     /* If we didn't send it, the server shouldn't send it */
951     if( ssl->conf->alpn_list == NULL )
952     {
953         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
954         mbedtls_ssl_send_alert_message(
955             ssl,
956             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
957             MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT );
958         return( MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION );
959     }
960 
961     /*
962      * opaque ProtocolName<1..2^8-1>;
963      *
964      * struct {
965      *     ProtocolName protocol_name_list<2..2^16-1>
966      * } ProtocolNameList;
967      *
968      * the "ProtocolNameList" MUST contain exactly one "ProtocolName"
969      */
970 
971     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
972     if( len < 4 )
973     {
974         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
975                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
976         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
977     }
978 
979     list_len = ( buf[0] << 8 ) | buf[1];
980     if( list_len != len - 2 )
981     {
982         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
983                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
984         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
985     }
986 
987     name_len = buf[2];
988     if( name_len != list_len - 1 )
989     {
990         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
991                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
992         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
993     }
994 
995     /* Check that the server chosen protocol was in our list and save it */
996     for( p = ssl->conf->alpn_list; *p != NULL; p++ )
997     {
998         if( name_len == strlen( *p ) &&
999             memcmp( buf + 3, *p, name_len ) == 0 )
1000         {
1001             ssl->alpn_chosen = *p;
1002             return( 0 );
1003         }
1004     }
1005 
1006     MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
1007     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1008                                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1009     return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1010 }
1011 #endif /* MBEDTLS_SSL_ALPN */
1012 
1013 #if defined(MBEDTLS_SSL_DTLS_SRTP)
1014 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_use_srtp_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1015 static int ssl_parse_use_srtp_ext( mbedtls_ssl_context *ssl,
1016                                    const unsigned char *buf,
1017                                    size_t len )
1018 {
1019     mbedtls_ssl_srtp_profile server_protection = MBEDTLS_TLS_SRTP_UNSET;
1020     size_t i, mki_len = 0;
1021     uint16_t server_protection_profile_value = 0;
1022 
1023     /* If use_srtp is not configured, just ignore the extension */
1024     if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
1025         ( ssl->conf->dtls_srtp_profile_list == NULL ) ||
1026         ( ssl->conf->dtls_srtp_profile_list_len == 0 ) )
1027         return( 0 );
1028 
1029     /* RFC 5764 section 4.1.1
1030      * uint8 SRTPProtectionProfile[2];
1031      *
1032      * struct {
1033      *   SRTPProtectionProfiles SRTPProtectionProfiles;
1034      *   opaque srtp_mki<0..255>;
1035      * } UseSRTPData;
1036 
1037      * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
1038      *
1039      */
1040     if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED )
1041     {
1042         mki_len = ssl->dtls_srtp_info.mki_len;
1043     }
1044 
1045     /*
1046      * Length is 5 + optional mki_value : one protection profile length (2 bytes)
1047      *                                      + protection profile (2 bytes)
1048      *                                      + mki_len(1 byte)
1049      *                                      and optional srtp_mki
1050      */
1051     if( ( len < 5 ) || ( len != ( buf[4] + 5u ) ) )
1052         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1053 
1054     /*
1055      * get the server protection profile
1056      */
1057 
1058     /*
1059      * protection profile length must be 0x0002 as we must have only
1060      * one protection profile in server Hello
1061      */
1062     if( (  buf[0] != 0 ) || ( buf[1] != 2 ) )
1063         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1064 
1065     server_protection_profile_value = ( buf[2] << 8 ) | buf[3];
1066     server_protection = mbedtls_ssl_check_srtp_profile_value(
1067                     server_protection_profile_value );
1068     if( server_protection != MBEDTLS_TLS_SRTP_UNSET )
1069     {
1070         MBEDTLS_SSL_DEBUG_MSG( 3, ( "found srtp profile: %s",
1071                                       mbedtls_ssl_get_srtp_profile_as_string(
1072                                               server_protection ) ) );
1073     }
1074 
1075     ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
1076 
1077     /*
1078      * Check we have the server profile in our list
1079      */
1080     for( i=0; i < ssl->conf->dtls_srtp_profile_list_len; i++)
1081     {
1082         if( server_protection == ssl->conf->dtls_srtp_profile_list[i] )
1083         {
1084             ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
1085             MBEDTLS_SSL_DEBUG_MSG( 3, ( "selected srtp profile: %s",
1086                                       mbedtls_ssl_get_srtp_profile_as_string(
1087                                               server_protection ) ) );
1088             break;
1089         }
1090     }
1091 
1092     /* If no match was found : server problem, it shall never answer with incompatible profile */
1093     if( ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET )
1094     {
1095         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1096                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1097         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1098     }
1099 
1100     /* If server does not use mki in its reply, make sure the client won't keep
1101      * one as negotiated */
1102     if( len == 5 )
1103     {
1104         ssl->dtls_srtp_info.mki_len = 0;
1105     }
1106 
1107     /*
1108      * RFC5764:
1109      *  If the client detects a nonzero-length MKI in the server's response
1110      *  that is different than the one the client offered, then the client
1111      *  MUST abort the handshake and SHOULD send an invalid_parameter alert.
1112      */
1113     if( len > 5  && ( buf[4] != mki_len ||
1114         ( memcmp( ssl->dtls_srtp_info.mki_value, &buf[5], mki_len ) ) ) )
1115     {
1116         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1117                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1118         return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
1119     }
1120 #if defined (MBEDTLS_DEBUG_C)
1121     if( len > 5 )
1122     {
1123         MBEDTLS_SSL_DEBUG_BUF( 3, "received mki", ssl->dtls_srtp_info.mki_value,
1124                                                   ssl->dtls_srtp_info.mki_len );
1125     }
1126 #endif
1127     return( 0 );
1128 }
1129 #endif /* MBEDTLS_SSL_DTLS_SRTP */
1130 
1131 /*
1132  * Parse HelloVerifyRequest.  Only called after verifying the HS type.
1133  */
1134 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1135 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_hello_verify_request(mbedtls_ssl_context * ssl)1136 static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
1137 {
1138     const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
1139     uint16_t dtls_legacy_version;
1140     unsigned char cookie_len;
1141 
1142     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
1143 
1144     /* Check that there is enough room for:
1145      * - 2 bytes of version
1146      * - 1 byte of cookie_len
1147      */
1148     if( mbedtls_ssl_hs_hdr_len( ssl ) + 3 > ssl->in_msglen )
1149     {
1150         MBEDTLS_SSL_DEBUG_MSG( 1,
1151             ( "incoming HelloVerifyRequest message is too short" ) );
1152         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1153                                     MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1154         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1155     }
1156 
1157     /*
1158      * struct {
1159      *   ProtocolVersion server_version;
1160      *   opaque cookie<0..2^8-1>;
1161      * } HelloVerifyRequest;
1162      */
1163     MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
1164     dtls_legacy_version = MBEDTLS_GET_UINT16_BE( p, 0 );
1165     p += 2;
1166 
1167     /*
1168      * Since the RFC is not clear on this point, accept DTLS 1.0 (0xfeff)
1169      * The DTLS 1.3 (current draft) renames ProtocolVersion server_version to
1170      * legacy_version and locks the value of legacy_version to 0xfefd (DTLS 1.2)
1171      */
1172     if( dtls_legacy_version != 0xfefd && dtls_legacy_version != 0xfeff )
1173     {
1174         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
1175 
1176         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1177                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
1178 
1179         return( MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION );
1180     }
1181 
1182     cookie_len = *p++;
1183     if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
1184     {
1185         MBEDTLS_SSL_DEBUG_MSG( 1,
1186             ( "cookie length does not match incoming message size" ) );
1187         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1188                                     MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1189         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1190     }
1191     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
1192 
1193     mbedtls_free( ssl->handshake->cookie );
1194 
1195     ssl->handshake->cookie = mbedtls_calloc( 1, cookie_len );
1196     if( ssl->handshake->cookie  == NULL )
1197     {
1198         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
1199         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
1200     }
1201 
1202     memcpy( ssl->handshake->cookie, p, cookie_len );
1203     ssl->handshake->verify_cookie_len = cookie_len;
1204 
1205     /* Start over at ClientHello */
1206     ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
1207     mbedtls_ssl_reset_checksum( ssl );
1208 
1209     mbedtls_ssl_recv_flight_completed( ssl );
1210 
1211     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
1212 
1213     return( 0 );
1214 }
1215 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1216 
1217 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_server_hello(mbedtls_ssl_context * ssl)1218 static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
1219 {
1220     int ret, i;
1221     size_t n;
1222     size_t ext_len;
1223     unsigned char *buf, *ext;
1224     unsigned char comp;
1225 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1226     int renegotiation_info_seen = 0;
1227 #endif
1228     int handshake_failure = 0;
1229     const mbedtls_ssl_ciphersuite_t *suite_info;
1230 
1231     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
1232 
1233     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
1234     {
1235         /* No alert on a read error. */
1236         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
1237         return( ret );
1238     }
1239 
1240     buf = ssl->in_msg;
1241 
1242     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
1243     {
1244 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1245         if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
1246         {
1247             ssl->renego_records_seen++;
1248 
1249             if( ssl->conf->renego_max_records >= 0 &&
1250                 ssl->renego_records_seen > ssl->conf->renego_max_records )
1251             {
1252                 MBEDTLS_SSL_DEBUG_MSG( 1,
1253                     ( "renegotiation requested, but not honored by server" ) );
1254                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
1255             }
1256 
1257             MBEDTLS_SSL_DEBUG_MSG( 1,
1258                 ( "non-handshake message during renegotiation" ) );
1259 
1260             ssl->keep_current_message = 1;
1261             return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
1262         }
1263 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1264 
1265         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1266         mbedtls_ssl_send_alert_message(
1267             ssl,
1268             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1269             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
1270         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
1271     }
1272 
1273 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1274     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1275     {
1276         if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
1277         {
1278             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
1279             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
1280             return( ssl_parse_hello_verify_request( ssl ) );
1281         }
1282         else
1283         {
1284             /* We made it through the verification process */
1285             mbedtls_free( ssl->handshake->cookie );
1286             ssl->handshake->cookie = NULL;
1287             ssl->handshake->verify_cookie_len = 0;
1288         }
1289     }
1290 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1291 
1292     if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
1293         buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
1294     {
1295         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1296         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1297                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1298         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1299     }
1300 
1301     /*
1302      *  0   .  1    server_version
1303      *  2   . 33    random (maybe including 4 bytes of Unix time)
1304      * 34   . 34    session_id length = n
1305      * 35   . 34+n  session_id
1306      * 35+n . 36+n  cipher_suite
1307      * 37+n . 37+n  compression_method
1308      *
1309      * 38+n . 39+n  extensions length (optional)
1310      * 40+n .  ..   extensions
1311      */
1312     buf += mbedtls_ssl_hs_hdr_len( ssl );
1313 
1314     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf, 2 );
1315     ssl->tls_version = mbedtls_ssl_read_version( buf, ssl->conf->transport );
1316     ssl->session_negotiate->tls_version = ssl->tls_version;
1317 
1318     if( ssl->tls_version < ssl->conf->min_tls_version ||
1319         ssl->tls_version > ssl->conf->max_tls_version )
1320     {
1321         MBEDTLS_SSL_DEBUG_MSG( 1,
1322             ( "server version out of bounds -  min: [0x%x], server: [0x%x], max: [0x%x]",
1323               (unsigned)ssl->conf->min_tls_version,
1324               (unsigned)ssl->tls_version,
1325               (unsigned)ssl->conf->max_tls_version ) );
1326 
1327         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1328                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
1329 
1330         return( MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION );
1331     }
1332 
1333     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
1334                                      ( (unsigned long) buf[2] << 24 ) |
1335                                      ( (unsigned long) buf[3] << 16 ) |
1336                                      ( (unsigned long) buf[4] <<  8 ) |
1337                                      ( (unsigned long) buf[5]       ) ) );
1338 
1339     memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
1340 
1341     n = buf[34];
1342 
1343     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, random bytes", buf + 2, 32 );
1344 
1345     if( n > 32 )
1346     {
1347         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1348         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1349                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1350         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1351     }
1352 
1353     if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
1354     {
1355         ext_len = ( ( buf[38 + n] <<  8 )
1356                   | ( buf[39 + n]       ) );
1357 
1358         if( ( ext_len > 0 && ext_len < 4 ) ||
1359             ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
1360         {
1361             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1362             mbedtls_ssl_send_alert_message(
1363                 ssl,
1364                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1365                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1366             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1367         }
1368     }
1369     else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
1370     {
1371         ext_len = 0;
1372     }
1373     else
1374     {
1375         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1376         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1377                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1378         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1379     }
1380 
1381     /* ciphersuite (used later) */
1382     i = ( buf[35 + n] << 8 ) | buf[36 + n];
1383 
1384     /*
1385      * Read and check compression
1386      */
1387     comp = buf[37 + n];
1388 
1389     if( comp != MBEDTLS_SSL_COMPRESS_NULL )
1390     {
1391         MBEDTLS_SSL_DEBUG_MSG( 1,
1392             ( "server hello, bad compression: %d", comp ) );
1393         mbedtls_ssl_send_alert_message(
1394             ssl,
1395             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1396             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1397         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1398     }
1399 
1400     /*
1401      * Initialize update checksum functions
1402      */
1403     ssl->handshake->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
1404     if( ssl->handshake->ciphersuite_info == NULL )
1405     {
1406         MBEDTLS_SSL_DEBUG_MSG( 1,
1407             ( "ciphersuite info for %04x not found", (unsigned int)i ) );
1408         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1409                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
1410         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1411     }
1412 
1413     mbedtls_ssl_optimize_checksum( ssl, ssl->handshake->ciphersuite_info );
1414 
1415     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n ) );
1416     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, session id", buf + 35, n );
1417 
1418     /*
1419      * Check if the session can be resumed
1420      */
1421     if( ssl->handshake->resume == 0 || n == 0 ||
1422 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1423         ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
1424 #endif
1425         ssl->session_negotiate->ciphersuite != i ||
1426         ssl->session_negotiate->id_len != n ||
1427         memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
1428     {
1429         ssl->state++;
1430         ssl->handshake->resume = 0;
1431 #if defined(MBEDTLS_HAVE_TIME)
1432         ssl->session_negotiate->start = mbedtls_time( NULL );
1433 #endif
1434         ssl->session_negotiate->ciphersuite = i;
1435         ssl->session_negotiate->id_len = n;
1436         memcpy( ssl->session_negotiate->id, buf + 35, n );
1437     }
1438     else
1439     {
1440         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
1441     }
1442 
1443     MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
1444                    ssl->handshake->resume ? "a" : "no" ) );
1445 
1446     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", (unsigned) i ) );
1447     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d",
1448                                 buf[37 + n] ) );
1449 
1450     /*
1451      * Perform cipher suite validation in same way as in ssl_write_client_hello.
1452      */
1453     i = 0;
1454     while( 1 )
1455     {
1456         if( ssl->conf->ciphersuite_list[i] == 0 )
1457         {
1458             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1459             mbedtls_ssl_send_alert_message(
1460                 ssl,
1461                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1462                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1463             return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
1464         }
1465 
1466         if( ssl->conf->ciphersuite_list[i++] ==
1467             ssl->session_negotiate->ciphersuite )
1468         {
1469             break;
1470         }
1471     }
1472 
1473     suite_info = mbedtls_ssl_ciphersuite_from_id(
1474         ssl->session_negotiate->ciphersuite );
1475     if( mbedtls_ssl_validate_ciphersuite( ssl, suite_info, ssl->tls_version,
1476                                           ssl->tls_version ) != 0 )
1477     {
1478         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1479         mbedtls_ssl_send_alert_message(
1480             ssl,
1481             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1482             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1483         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1484     }
1485 
1486     MBEDTLS_SSL_DEBUG_MSG( 3,
1487         ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
1488 
1489 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
1490     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA &&
1491         ssl->tls_version == MBEDTLS_SSL_VERSION_TLS1_2 )
1492     {
1493         ssl->handshake->ecrs_enabled = 1;
1494     }
1495 #endif
1496 
1497     if( comp != MBEDTLS_SSL_COMPRESS_NULL )
1498     {
1499         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1500         mbedtls_ssl_send_alert_message(
1501             ssl,
1502             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1503             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1504         return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
1505     }
1506 
1507     ext = buf + 40 + n;
1508 
1509     MBEDTLS_SSL_DEBUG_MSG( 2,
1510         ( "server hello, total extension length: %" MBEDTLS_PRINTF_SIZET, ext_len ) );
1511 
1512     while( ext_len )
1513     {
1514         unsigned int ext_id   = ( ( ext[0] <<  8 )
1515                                 | ( ext[1]       ) );
1516         unsigned int ext_size = ( ( ext[2] <<  8 )
1517                                 | ( ext[3]       ) );
1518 
1519         if( ext_size + 4 > ext_len )
1520         {
1521             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1522             mbedtls_ssl_send_alert_message(
1523                 ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1524                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1525             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1526         }
1527 
1528         switch( ext_id )
1529         {
1530         case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1531             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
1532 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1533             renegotiation_info_seen = 1;
1534 #endif
1535 
1536             if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
1537                                                       ext_size ) ) != 0 )
1538                 return( ret );
1539 
1540             break;
1541 
1542 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1543         case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1544             MBEDTLS_SSL_DEBUG_MSG( 3,
1545                 ( "found max_fragment_length extension" ) );
1546 
1547             if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
1548                             ext + 4, ext_size ) ) != 0 )
1549             {
1550                 return( ret );
1551             }
1552 
1553             break;
1554 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1555 
1556 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1557         case MBEDTLS_TLS_EXT_CID:
1558             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) );
1559 
1560             if( ( ret = ssl_parse_cid_ext( ssl,
1561                                            ext + 4,
1562                                            ext_size ) ) != 0 )
1563             {
1564                 return( ret );
1565             }
1566 
1567             break;
1568 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1569 
1570 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1571         case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
1572             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
1573 
1574             if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
1575                             ext + 4, ext_size ) ) != 0 )
1576             {
1577                 return( ret );
1578             }
1579 
1580             break;
1581 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1582 
1583 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1584         case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
1585             MBEDTLS_SSL_DEBUG_MSG( 3,
1586                 ( "found extended_master_secret extension" ) );
1587 
1588             if( ( ret = ssl_parse_extended_ms_ext( ssl,
1589                             ext + 4, ext_size ) ) != 0 )
1590             {
1591                 return( ret );
1592             }
1593 
1594             break;
1595 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1596 
1597 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1598         case MBEDTLS_TLS_EXT_SESSION_TICKET:
1599             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
1600 
1601             if( ( ret = ssl_parse_session_ticket_ext( ssl,
1602                             ext + 4, ext_size ) ) != 0 )
1603             {
1604                 return( ret );
1605             }
1606 
1607             break;
1608 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1609 
1610 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1611     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1612         case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1613             MBEDTLS_SSL_DEBUG_MSG( 3,
1614                 ( "found supported_point_formats extension" ) );
1615 
1616             if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
1617                             ext + 4, ext_size ) ) != 0 )
1618             {
1619                 return( ret );
1620             }
1621 
1622             break;
1623 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
1624           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1625 
1626 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1627         case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1628             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
1629 
1630             if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
1631                             ext + 4, ext_size ) ) != 0 )
1632             {
1633                 return( ret );
1634             }
1635 
1636             break;
1637 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1638 
1639 #if defined(MBEDTLS_SSL_ALPN)
1640         case MBEDTLS_TLS_EXT_ALPN:
1641             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
1642 
1643             if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
1644                 return( ret );
1645 
1646             break;
1647 #endif /* MBEDTLS_SSL_ALPN */
1648 
1649 #if defined(MBEDTLS_SSL_DTLS_SRTP)
1650         case MBEDTLS_TLS_EXT_USE_SRTP:
1651             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found use_srtp extension" ) );
1652 
1653             if( ( ret = ssl_parse_use_srtp_ext( ssl, ext + 4, ext_size ) ) != 0 )
1654                 return( ret );
1655 
1656             break;
1657 #endif /* MBEDTLS_SSL_DTLS_SRTP */
1658 
1659         default:
1660             MBEDTLS_SSL_DEBUG_MSG( 3,
1661                 ( "unknown extension found: %u (ignoring)", ext_id ) );
1662         }
1663 
1664         ext_len -= 4 + ext_size;
1665         ext += 4 + ext_size;
1666 
1667         if( ext_len > 0 && ext_len < 4 )
1668         {
1669             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1670             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1671         }
1672     }
1673 
1674     /*
1675      * mbedtls_ssl_derive_keys() has to be called after the parsing of the
1676      * extensions. It sets the transform data for the resumed session which in
1677      * case of DTLS includes the server CID extracted from the CID extension.
1678      */
1679     if( ssl->handshake->resume )
1680     {
1681         if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
1682         {
1683             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
1684             mbedtls_ssl_send_alert_message(
1685                 ssl,
1686                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1687                 MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
1688             return( ret );
1689         }
1690     }
1691 
1692     /*
1693      * Renegotiation security checks
1694      */
1695     if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1696         ssl->conf->allow_legacy_renegotiation ==
1697         MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
1698     {
1699         MBEDTLS_SSL_DEBUG_MSG( 1,
1700             ( "legacy renegotiation, breaking off handshake" ) );
1701         handshake_failure = 1;
1702     }
1703 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1704     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1705              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1706              renegotiation_info_seen == 0 )
1707     {
1708         MBEDTLS_SSL_DEBUG_MSG( 1,
1709             ( "renegotiation_info extension missing (secure)" ) );
1710         handshake_failure = 1;
1711     }
1712     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1713              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1714              ssl->conf->allow_legacy_renegotiation ==
1715              MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
1716     {
1717         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
1718         handshake_failure = 1;
1719     }
1720     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1721              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1722              renegotiation_info_seen == 1 )
1723     {
1724         MBEDTLS_SSL_DEBUG_MSG( 1,
1725             ( "renegotiation_info extension present (legacy)" ) );
1726         handshake_failure = 1;
1727     }
1728 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1729 
1730     if( handshake_failure == 1 )
1731     {
1732         mbedtls_ssl_send_alert_message(
1733             ssl,
1734             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1735             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1736         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1737     }
1738 
1739     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
1740 
1741     return( 0 );
1742 }
1743 
1744 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
1745     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1746 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_server_dh_params(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)1747 static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl,
1748                                        unsigned char **p,
1749                                        unsigned char *end )
1750 {
1751     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1752     size_t dhm_actual_bitlen;
1753 
1754     /*
1755      * Ephemeral DH parameters:
1756      *
1757      * struct {
1758      *     opaque dh_p<1..2^16-1>;
1759      *     opaque dh_g<1..2^16-1>;
1760      *     opaque dh_Ys<1..2^16-1>;
1761      * } ServerDHParams;
1762      */
1763     if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx,
1764                                          p, end ) ) != 0 )
1765     {
1766         MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
1767         return( ret );
1768     }
1769 
1770     dhm_actual_bitlen = mbedtls_dhm_get_bitlen( &ssl->handshake->dhm_ctx );
1771     if( dhm_actual_bitlen < ssl->conf->dhm_min_bitlen )
1772     {
1773         MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %" MBEDTLS_PRINTF_SIZET " < %u",
1774                                     dhm_actual_bitlen,
1775                                     ssl->conf->dhm_min_bitlen ) );
1776         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1777     }
1778 
1779     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P  );
1780     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G  );
1781     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
1782 
1783     return( ret );
1784 }
1785 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
1786           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
1787 
1788 #if defined(MBEDTLS_USE_PSA_CRYPTO)
1789 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   ||   \
1790     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)   ||   \
1791     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
1792 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_server_ecdh_params(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)1793 static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
1794                                              unsigned char **p,
1795                                              unsigned char *end )
1796 {
1797     uint16_t tls_id;
1798     size_t ecdh_bits = 0;
1799     uint8_t ecpoint_len;
1800     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1801 
1802     /*
1803      * struct {
1804      *     ECParameters curve_params;
1805      *     ECPoint      public;
1806      * } ServerECDHParams;
1807      *
1808      *  1       curve_type (must be "named_curve")
1809      *  2..3    NamedCurve
1810      *  4       ECPoint.len
1811      *  5+      ECPoint contents
1812      */
1813     if( end - *p < 4 )
1814         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1815 
1816     /* First byte is curve_type; only named_curve is handled */
1817     if( *(*p)++ != MBEDTLS_ECP_TLS_NAMED_CURVE )
1818         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1819 
1820     /* Next two bytes are the namedcurve value */
1821     tls_id = *(*p)++;
1822     tls_id <<= 8;
1823     tls_id |= *(*p)++;
1824 
1825     /* Check it's a curve we offered */
1826     if( mbedtls_ssl_check_curve_tls_id( ssl, tls_id ) != 0 )
1827     {
1828         MBEDTLS_SSL_DEBUG_MSG( 2,
1829             ( "bad server key exchange message (ECDHE curve): %u",
1830               (unsigned) tls_id ) );
1831         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1832     }
1833 
1834     /* Convert EC group to PSA key type. */
1835     if( ( handshake->ecdh_psa_type =
1836           mbedtls_psa_parse_tls_ecc_group( tls_id, &ecdh_bits ) ) == 0 )
1837     {
1838         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1839     }
1840     handshake->ecdh_bits = ecdh_bits;
1841 
1842     /* Keep a copy of the peer's public key */
1843     ecpoint_len = *(*p)++;
1844     if( (size_t)( end - *p ) < ecpoint_len )
1845         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1846 
1847     if( ecpoint_len > sizeof( handshake->ecdh_psa_peerkey ) )
1848         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1849 
1850     memcpy( handshake->ecdh_psa_peerkey, *p, ecpoint_len );
1851     handshake->ecdh_psa_peerkey_len = ecpoint_len;
1852     *p += ecpoint_len;
1853 
1854     return( 0 );
1855 }
1856 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED   ||
1857           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED   ||
1858           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
1859 #else
1860 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED)   ||   \
1861     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)    ||   \
1862     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)   ||   \
1863     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||   \
1864     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
1865 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_check_server_ecdh_params(const mbedtls_ssl_context * ssl)1866 static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
1867 {
1868     const mbedtls_ecp_curve_info *curve_info;
1869     mbedtls_ecp_group_id grp_id;
1870 #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
1871     grp_id = ssl->handshake->ecdh_ctx.grp.id;
1872 #else
1873     grp_id = ssl->handshake->ecdh_ctx.grp_id;
1874 #endif
1875 
1876     curve_info = mbedtls_ecp_curve_info_from_grp_id( grp_id );
1877     if( curve_info == NULL )
1878     {
1879         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1880         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1881     }
1882 
1883     MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
1884 
1885     if( mbedtls_ssl_check_curve( ssl, grp_id ) != 0 )
1886         return( -1 );
1887 
1888     MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
1889                             MBEDTLS_DEBUG_ECDH_QP );
1890 
1891     return( 0 );
1892 }
1893 
1894 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED   ||
1895           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED    ||
1896           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED   ||
1897           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
1898           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
1899 
1900 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
1901     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||     \
1902     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
1903 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_server_ecdh_params(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)1904 static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
1905                                          unsigned char **p,
1906                                          unsigned char *end )
1907 {
1908     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1909 
1910     /*
1911      * Ephemeral ECDH parameters:
1912      *
1913      * struct {
1914      *     ECParameters curve_params;
1915      *     ECPoint      public;
1916      * } ServerECDHParams;
1917      */
1918     if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
1919                                   (const unsigned char **) p, end ) ) != 0 )
1920     {
1921         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
1922 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
1923         if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
1924             ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
1925 #endif
1926         return( ret );
1927     }
1928 
1929     if( ssl_check_server_ecdh_params( ssl ) != 0 )
1930     {
1931         MBEDTLS_SSL_DEBUG_MSG( 1,
1932             ( "bad server key exchange message (ECDHE curve)" ) );
1933         return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
1934     }
1935 
1936     return( ret );
1937 }
1938 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||     \
1939           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||     \
1940           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
1941 #endif /* !MBEDTLS_USE_PSA_CRYPTO */
1942 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1943 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_server_psk_hint(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)1944 static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
1945                                       unsigned char **p,
1946                                       unsigned char *end )
1947 {
1948     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1949     uint16_t  len;
1950     ((void) ssl);
1951 
1952     /*
1953      * PSK parameters:
1954      *
1955      * opaque psk_identity_hint<0..2^16-1>;
1956      */
1957     if( end - (*p) < 2 )
1958     {
1959         MBEDTLS_SSL_DEBUG_MSG( 1,
1960             ( "bad server key exchange message (psk_identity_hint length)" ) );
1961         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1962     }
1963     len = (*p)[0] << 8 | (*p)[1];
1964     *p += 2;
1965 
1966     if( end - (*p) < len )
1967     {
1968         MBEDTLS_SSL_DEBUG_MSG( 1,
1969             ( "bad server key exchange message (psk_identity_hint length)" ) );
1970         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
1971     }
1972 
1973     /*
1974      * Note: we currently ignore the PSK identity hint, as we only allow one
1975      * PSK to be provisioned on the client. This could be changed later if
1976      * someone needs that feature.
1977      */
1978     *p += len;
1979     ret = 0;
1980 
1981     return( ret );
1982 }
1983 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
1984 
1985 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
1986     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1987 /*
1988  * Generate a pre-master secret and encrypt it with the server's RSA key
1989  */
1990 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_encrypted_pms(mbedtls_ssl_context * ssl,size_t offset,size_t * olen,size_t pms_offset)1991 static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
1992                                     size_t offset, size_t *olen,
1993                                     size_t pms_offset )
1994 {
1995     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1996     size_t len_bytes = 2;
1997     unsigned char *p = ssl->handshake->premaster + pms_offset;
1998     mbedtls_pk_context * peer_pk;
1999 
2000     if( offset + len_bytes > MBEDTLS_SSL_OUT_CONTENT_LEN )
2001     {
2002         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
2003         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2004     }
2005 
2006     /*
2007      * Generate (part of) the pre-master as
2008      *  struct {
2009      *      ProtocolVersion client_version;
2010      *      opaque random[46];
2011      *  } PreMasterSecret;
2012      */
2013     mbedtls_ssl_write_version( p, ssl->conf->transport,
2014                                MBEDTLS_SSL_VERSION_TLS1_2 );
2015 
2016     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
2017     {
2018         MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
2019         return( ret );
2020     }
2021 
2022     ssl->handshake->pmslen = 48;
2023 
2024 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2025     peer_pk = &ssl->handshake->peer_pubkey;
2026 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2027     if( ssl->session_negotiate->peer_cert == NULL )
2028     {
2029         /* Should never happen */
2030         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2031         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2032     }
2033     peer_pk = &ssl->session_negotiate->peer_cert->pk;
2034 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2035 
2036     /*
2037      * Now write it out, encrypted
2038      */
2039     if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_RSA ) )
2040     {
2041         MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
2042         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2043     }
2044 
2045     if( ( ret = mbedtls_pk_encrypt( peer_pk,
2046                             p, ssl->handshake->pmslen,
2047                             ssl->out_msg + offset + len_bytes, olen,
2048                             MBEDTLS_SSL_OUT_CONTENT_LEN - offset - len_bytes,
2049                             ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2050     {
2051         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
2052         return( ret );
2053     }
2054 
2055     if( len_bytes == 2 )
2056     {
2057         MBEDTLS_PUT_UINT16_BE( *olen, ssl->out_msg, offset );
2058         *olen += 2;
2059     }
2060 
2061 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2062     /* We don't need the peer's public key anymore. Free it. */
2063     mbedtls_pk_free( peer_pk );
2064 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2065     return( 0 );
2066 }
2067 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
2068           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2069 
2070 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2071     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2072 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_get_ecdh_params_from_cert(mbedtls_ssl_context * ssl)2073 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
2074 {
2075     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2076     const mbedtls_ecp_keypair *peer_key;
2077     mbedtls_pk_context * peer_pk;
2078 
2079 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2080     peer_pk = &ssl->handshake->peer_pubkey;
2081 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2082     if( ssl->session_negotiate->peer_cert == NULL )
2083     {
2084         /* Should never happen */
2085         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2086         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2087     }
2088     peer_pk = &ssl->session_negotiate->peer_cert->pk;
2089 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2090 
2091     /* This is a public key, so it can't be opaque, so can_do() is a good
2092      * enough check to ensure pk_ec() is safe to use below. */
2093     if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECKEY ) )
2094     {
2095         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
2096         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2097     }
2098 
2099     peer_key = mbedtls_pk_ec( *peer_pk );
2100 
2101 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2102     size_t ecdh_bits = 0;
2103     size_t olen = 0;
2104 
2105     if( mbedtls_ssl_check_curve( ssl, peer_key->grp.id ) != 0 )
2106     {
2107         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
2108         return( MBEDTLS_ERR_SSL_BAD_CERTIFICATE );
2109     }
2110 
2111     ssl->handshake->ecdh_psa_type =
2112         PSA_KEY_TYPE_ECC_KEY_PAIR( mbedtls_ecc_group_to_psa( peer_key->grp.id,
2113                                                              &ecdh_bits ) );
2114 
2115     if( ssl->handshake->ecdh_psa_type == 0 || ecdh_bits > 0xffff )
2116     {
2117         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Invalid ecc group conversion to psa." ) );
2118         return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
2119     }
2120 
2121     ssl->handshake->ecdh_bits = (uint16_t) ecdh_bits;
2122 
2123     /* Store peer's public key in psa format. */
2124     ret = mbedtls_ecp_point_write_binary( &peer_key->grp, &peer_key->Q,
2125                                           MBEDTLS_ECP_PF_UNCOMPRESSED, &olen,
2126                                           ssl->handshake->ecdh_psa_peerkey,
2127                                           MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH );
2128 
2129     if ( ret != 0 )
2130     {
2131         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecp_point_write_binary" ), ret );
2132         return( ret );
2133     }
2134 
2135     ssl->handshake->ecdh_psa_peerkey_len = olen;
2136 #else
2137     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
2138                                  MBEDTLS_ECDH_THEIRS ) ) != 0 )
2139     {
2140         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
2141         return( ret );
2142     }
2143 
2144     if( ssl_check_server_ecdh_params( ssl ) != 0 )
2145     {
2146         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
2147         return( MBEDTLS_ERR_SSL_BAD_CERTIFICATE );
2148     }
2149 #endif
2150 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2151     /* We don't need the peer's public key anymore. Free it,
2152      * so that more RAM is available for upcoming expensive
2153      * operations like ECDHE. */
2154     mbedtls_pk_free( peer_pk );
2155 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2156 
2157     return( ret );
2158 }
2159 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
2160           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2161 
2162 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_server_key_exchange(mbedtls_ssl_context * ssl)2163 static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
2164 {
2165     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2166     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2167         ssl->handshake->ciphersuite_info;
2168     unsigned char *p = NULL, *end = NULL;
2169 
2170     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
2171 
2172 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
2173     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
2174     {
2175         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
2176         ssl->state++;
2177         return( 0 );
2178     }
2179     ((void) p);
2180     ((void) end);
2181 #endif
2182 
2183 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2184     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2185     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2186         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
2187     {
2188         if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
2189         {
2190             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
2191             mbedtls_ssl_send_alert_message(
2192                 ssl,
2193                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2194                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2195             return( ret );
2196         }
2197 
2198         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
2199         ssl->state++;
2200         return( 0 );
2201     }
2202     ((void) p);
2203     ((void) end);
2204 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2205           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2206 
2207 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2208     if( ssl->handshake->ecrs_enabled &&
2209         ssl->handshake->ecrs_state == ssl_ecrs_ske_start_processing )
2210     {
2211         goto start_processing;
2212     }
2213 #endif
2214 
2215     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
2216     {
2217         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2218         return( ret );
2219     }
2220 
2221     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2222     {
2223         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2224         mbedtls_ssl_send_alert_message(
2225             ssl,
2226             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2227             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2228         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2229     }
2230 
2231     /*
2232      * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
2233      * doesn't use a psk_identity_hint
2234      */
2235     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
2236     {
2237         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2238             ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2239         {
2240             /* Current message is probably either
2241              * CertificateRequest or ServerHelloDone */
2242             ssl->keep_current_message = 1;
2243             goto exit;
2244         }
2245 
2246         MBEDTLS_SSL_DEBUG_MSG( 1,
2247             ( "server key exchange message must not be skipped" ) );
2248         mbedtls_ssl_send_alert_message(
2249             ssl,
2250             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2251             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2252 
2253         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2254     }
2255 
2256 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2257     if( ssl->handshake->ecrs_enabled )
2258         ssl->handshake->ecrs_state = ssl_ecrs_ske_start_processing;
2259 
2260 start_processing:
2261 #endif
2262     p   = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
2263     end = ssl->in_msg + ssl->in_hslen;
2264     MBEDTLS_SSL_DEBUG_BUF( 3,   "server key exchange", p, end - p );
2265 
2266 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
2267     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2268         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
2269         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2270         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
2271     {
2272         if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
2273         {
2274             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2275             mbedtls_ssl_send_alert_message(
2276                 ssl,
2277                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2278                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2279             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2280         }
2281     } /* FALLTHROUGH */
2282 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
2283 
2284 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) ||                       \
2285     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2286     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2287         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2288         ; /* nothing more to do */
2289     else
2290 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
2291           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2292 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2293     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
2294     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
2295         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
2296     {
2297         if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
2298         {
2299             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2300             mbedtls_ssl_send_alert_message(
2301                 ssl,
2302                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2303                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2304             return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
2305         }
2306     }
2307     else
2308 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2309           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2310 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
2311     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||     \
2312     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
2313     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2314         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
2315         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
2316     {
2317         if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
2318         {
2319             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2320             mbedtls_ssl_send_alert_message(
2321                 ssl,
2322                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2323                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2324             return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
2325         }
2326     }
2327     else
2328 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2329           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
2330           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2331 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2332     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
2333     {
2334 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2335         /*
2336          * The first 3 bytes are:
2337          * [0] MBEDTLS_ECP_TLS_NAMED_CURVE
2338          * [1, 2] elliptic curve's TLS ID
2339          *
2340          * However since we only support secp256r1 for now, we check only
2341          * that TLS ID here
2342          */
2343         uint16_t read_tls_id = MBEDTLS_GET_UINT16_BE( p, 1 );
2344         const mbedtls_ecp_curve_info *curve_info;
2345 
2346         if( ( curve_info = mbedtls_ecp_curve_info_from_grp_id(
2347                                 MBEDTLS_ECP_DP_SECP256R1 ) ) == NULL )
2348         {
2349             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2350         }
2351 
2352         if( ( *p != MBEDTLS_ECP_TLS_NAMED_CURVE ) ||
2353             ( read_tls_id != curve_info->tls_id ) )
2354         {
2355             return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
2356         }
2357 
2358         p += 3;
2359 
2360         if( ( ret = mbedtls_psa_ecjpake_read_round(
2361                         &ssl->handshake->psa_pake_ctx, p, end - p,
2362                         MBEDTLS_ECJPAKE_ROUND_TWO ) ) != 0 )
2363         {
2364             psa_destroy_key( ssl->handshake->psa_pake_password );
2365             psa_pake_abort( &ssl->handshake->psa_pake_ctx );
2366 
2367             MBEDTLS_SSL_DEBUG_RET( 1, "psa_pake_input round two", ret );
2368             mbedtls_ssl_send_alert_message(
2369                 ssl,
2370                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2371                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2372             return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
2373         }
2374 #else
2375         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
2376                                               p, end - p );
2377         if( ret != 0 )
2378         {
2379             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
2380             mbedtls_ssl_send_alert_message(
2381                 ssl,
2382                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2383                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2384             return( MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE );
2385         }
2386 #endif /* MBEDTLS_USE_PSA_CRYPTO */
2387     }
2388     else
2389 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2390     {
2391         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2392         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2393     }
2394 
2395 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2396     if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
2397     {
2398         size_t sig_len, hashlen;
2399         unsigned char hash[MBEDTLS_HASH_MAX_SIZE];
2400 
2401         mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
2402         mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
2403         unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
2404         size_t params_len = p - params;
2405         void *rs_ctx = NULL;
2406         uint16_t sig_alg;
2407 
2408         mbedtls_pk_context * peer_pk;
2409 
2410 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2411         peer_pk = &ssl->handshake->peer_pubkey;
2412 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2413         if( ssl->session_negotiate->peer_cert == NULL )
2414         {
2415             /* Should never happen */
2416             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2417             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2418         }
2419         peer_pk = &ssl->session_negotiate->peer_cert->pk;
2420 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2421 
2422         /*
2423          * Handle the digitally-signed structure
2424          */
2425         MBEDTLS_SSL_CHK_BUF_READ_PTR( p, end, 2 );
2426         sig_alg = MBEDTLS_GET_UINT16_BE( p, 0 );
2427         if( mbedtls_ssl_get_pk_type_and_md_alg_from_sig_alg(
2428                             sig_alg, &pk_alg, &md_alg ) != 0 &&
2429             ! mbedtls_ssl_sig_alg_is_offered( ssl, sig_alg ) &&
2430             ! mbedtls_ssl_sig_alg_is_supported( ssl, sig_alg ) )
2431         {
2432             MBEDTLS_SSL_DEBUG_MSG( 1,
2433                 ( "bad server key exchange message" ) );
2434             mbedtls_ssl_send_alert_message(
2435                 ssl,
2436                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2437                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2438             return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
2439         }
2440         p += 2;
2441 
2442         if( !mbedtls_pk_can_do( peer_pk, pk_alg ) )
2443         {
2444             MBEDTLS_SSL_DEBUG_MSG( 1,
2445                 ( "bad server key exchange message" ) );
2446             mbedtls_ssl_send_alert_message(
2447                 ssl,
2448                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2449                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2450             return( MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER );
2451         }
2452 
2453         /*
2454          * Read signature
2455          */
2456 
2457         if( p > end - 2 )
2458         {
2459             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2460             mbedtls_ssl_send_alert_message(
2461                 ssl,
2462                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2463                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2464             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2465         }
2466         sig_len = ( p[0] << 8 ) | p[1];
2467         p += 2;
2468 
2469         if( p != end - sig_len )
2470         {
2471             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2472             mbedtls_ssl_send_alert_message(
2473                 ssl,
2474                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2475                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2476             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2477         }
2478 
2479         MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
2480 
2481         /*
2482          * Compute the hash that has been signed
2483          */
2484         if( md_alg != MBEDTLS_MD_NONE )
2485         {
2486             ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,
2487                                                           params, params_len,
2488                                                           md_alg );
2489             if( ret != 0 )
2490                 return( ret );
2491         }
2492         else
2493         {
2494             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2495             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2496         }
2497 
2498         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen );
2499 
2500         /*
2501          * Verify signature
2502          */
2503         if( !mbedtls_pk_can_do( peer_pk, pk_alg ) )
2504         {
2505             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2506             mbedtls_ssl_send_alert_message(
2507                 ssl,
2508                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2509                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2510             return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2511         }
2512 
2513 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2514         if( ssl->handshake->ecrs_enabled )
2515             rs_ctx = &ssl->handshake->ecrs_ctx.pk;
2516 #endif
2517 
2518 #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
2519         if( pk_alg == MBEDTLS_PK_RSASSA_PSS )
2520         {
2521             mbedtls_pk_rsassa_pss_options rsassa_pss_options;
2522             rsassa_pss_options.mgf1_hash_id = md_alg;
2523             rsassa_pss_options.expected_salt_len =
2524                                     mbedtls_hash_info_get_size( md_alg );
2525             if( rsassa_pss_options.expected_salt_len == 0 )
2526                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2527 
2528             ret = mbedtls_pk_verify_ext( pk_alg, &rsassa_pss_options,
2529                                          peer_pk,
2530                                          md_alg, hash, hashlen,
2531                                          p, sig_len );
2532         }
2533         else
2534 #endif /* MBEDTLS_X509_RSASSA_PSS_SUPPORT */
2535             ret = mbedtls_pk_verify_restartable( peer_pk,
2536                         md_alg, hash, hashlen, p, sig_len, rs_ctx );
2537 
2538         if( ret != 0 )
2539         {
2540             int send_alert_msg = 1;
2541 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2542             send_alert_msg = ( ret != MBEDTLS_ERR_ECP_IN_PROGRESS );
2543 #endif
2544             if( send_alert_msg )
2545                 mbedtls_ssl_send_alert_message(
2546                     ssl,
2547                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2548                     MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
2549             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
2550 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2551             if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2552                 ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
2553 #endif
2554             return( ret );
2555         }
2556 
2557 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2558         /* We don't need the peer's public key anymore. Free it,
2559          * so that more RAM is available for upcoming expensive
2560          * operations like ECDHE. */
2561         mbedtls_pk_free( peer_pk );
2562 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2563     }
2564 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
2565 
2566 exit:
2567     ssl->state++;
2568 
2569     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
2570 
2571     return( 0 );
2572 }
2573 
2574 #if ! defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
2575 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_certificate_request(mbedtls_ssl_context * ssl)2576 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
2577 {
2578     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2579         ssl->handshake->ciphersuite_info;
2580 
2581     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
2582 
2583     if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
2584     {
2585         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
2586         ssl->state++;
2587         return( 0 );
2588     }
2589 
2590     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2591     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2592 }
2593 #else /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
2594 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_certificate_request(mbedtls_ssl_context * ssl)2595 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
2596 {
2597     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2598     unsigned char *buf;
2599     size_t n = 0;
2600     size_t cert_type_len = 0, dn_len = 0;
2601     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2602         ssl->handshake->ciphersuite_info;
2603     size_t sig_alg_len;
2604 #if defined(MBEDTLS_DEBUG_C)
2605         unsigned char *sig_alg;
2606         unsigned char *dn;
2607 #endif
2608 
2609     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
2610 
2611     if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
2612     {
2613         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
2614         ssl->state++;
2615         return( 0 );
2616     }
2617 
2618     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
2619     {
2620         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2621         return( ret );
2622     }
2623 
2624     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2625     {
2626         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2627         mbedtls_ssl_send_alert_message(
2628             ssl,
2629             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2630             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2631         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2632     }
2633 
2634     ssl->state++;
2635     ssl->handshake->client_auth =
2636                     ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
2637 
2638     MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
2639                         ssl->handshake->client_auth ? "a" : "no" ) );
2640 
2641     if( ssl->handshake->client_auth == 0 )
2642     {
2643         /* Current message is probably the ServerHelloDone */
2644         ssl->keep_current_message = 1;
2645         goto exit;
2646     }
2647 
2648     /*
2649      *  struct {
2650      *      ClientCertificateType certificate_types<1..2^8-1>;
2651      *      SignatureAndHashAlgorithm
2652      *        supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
2653      *      DistinguishedName certificate_authorities<0..2^16-1>;
2654      *  } CertificateRequest;
2655      *
2656      *  Since we only support a single certificate on clients, let's just
2657      *  ignore all the information that's supposed to help us pick a
2658      *  certificate.
2659      *
2660      *  We could check that our certificate matches the request, and bail out
2661      *  if it doesn't, but it's simpler to just send the certificate anyway,
2662      *  and give the server the opportunity to decide if it should terminate
2663      *  the connection when it doesn't like our certificate.
2664      *
2665      *  Same goes for the hash in TLS 1.2's signature_algorithms: at this
2666      *  point we only have one hash available (see comments in
2667      *  write_certificate_verify), so let's just use what we have.
2668      *
2669      *  However, we still minimally parse the message to check it is at least
2670      *  superficially sane.
2671      */
2672     buf = ssl->in_msg;
2673 
2674     /* certificate_types */
2675     if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) )
2676     {
2677         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2678         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2679                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2680         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2681     }
2682     cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
2683     n = cert_type_len;
2684 
2685     /*
2686      * In the subsequent code there are two paths that read from buf:
2687      *     * the length of the signature algorithms field (if minor version of
2688      *       SSL is 3),
2689      *     * distinguished name length otherwise.
2690      * Both reach at most the index:
2691      *    ...hdr_len + 2 + n,
2692      * therefore the buffer length at this point must be greater than that
2693      * regardless of the actual code path.
2694      */
2695     if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
2696     {
2697         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2698         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2699                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2700         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2701     }
2702 
2703     /* supported_signature_algorithms */
2704     sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
2705                   | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]   ) );
2706 
2707     /*
2708      * The furthest access in buf is in the loop few lines below:
2709      *     sig_alg[i + 1],
2710      * where:
2711      *     sig_alg = buf + ...hdr_len + 3 + n,
2712      *     max(i) = sig_alg_len - 1.
2713      * Therefore the furthest access is:
2714      *     buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1],
2715      * which reduces to:
2716      *     buf[...hdr_len + 3 + n + sig_alg_len],
2717      * which is one less than we need the buf to be.
2718      */
2719     if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len )
2720     {
2721         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2722         mbedtls_ssl_send_alert_message(
2723             ssl,
2724             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2725             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2726         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2727     }
2728 
2729 #if defined(MBEDTLS_DEBUG_C)
2730     sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
2731     for( size_t i = 0; i < sig_alg_len; i += 2 )
2732     {
2733         MBEDTLS_SSL_DEBUG_MSG( 3,
2734             ( "Supported Signature Algorithm found: %02x %02x",
2735               sig_alg[i], sig_alg[i + 1]  ) );
2736     }
2737 #endif
2738 
2739     n += 2 + sig_alg_len;
2740 
2741     /* certificate_authorities */
2742     dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
2743              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
2744 
2745     n += dn_len;
2746     if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
2747     {
2748         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2749         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2750                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2751         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2752     }
2753 
2754 #if defined(MBEDTLS_DEBUG_C)
2755     dn = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n - dn_len;
2756     for( size_t i = 0, dni_len = 0; i < dn_len; i += 2 + dni_len )
2757     {
2758         unsigned char *p = dn + i + 2;
2759         mbedtls_x509_name name;
2760         size_t asn1_len;
2761         char s[MBEDTLS_X509_MAX_DN_NAME_SIZE];
2762         memset( &name, 0, sizeof( name ) );
2763         dni_len = MBEDTLS_GET_UINT16_BE( dn + i, 0 );
2764         if( dni_len > dn_len - i - 2 ||
2765             mbedtls_asn1_get_tag( &p, p + dni_len, &asn1_len,
2766               MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE ) != 0 ||
2767             mbedtls_x509_get_name( &p, p + asn1_len, &name ) != 0 )
2768         {
2769             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2770             mbedtls_ssl_send_alert_message(
2771                 ssl,
2772                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2773                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2774             return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2775         }
2776         MBEDTLS_SSL_DEBUG_MSG( 3,
2777             ( "DN hint: %.*s",
2778               mbedtls_x509_dn_gets( s, sizeof(s), &name ), s ) );
2779         mbedtls_asn1_free_named_data_list_shallow( name.next );
2780     }
2781 #endif
2782 
2783 exit:
2784     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
2785 
2786     return( 0 );
2787 }
2788 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
2789 
2790 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_server_hello_done(mbedtls_ssl_context * ssl)2791 static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
2792 {
2793     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2794 
2795     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
2796 
2797     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
2798     {
2799         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2800         return( ret );
2801     }
2802 
2803     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2804     {
2805         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
2806         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2807     }
2808 
2809     if( ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ||
2810         ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
2811     {
2812         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
2813         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2814                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2815         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
2816     }
2817 
2818     ssl->state++;
2819 
2820 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2821     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2822         mbedtls_ssl_recv_flight_completed( ssl );
2823 #endif
2824 
2825     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
2826 
2827     return( 0 );
2828 }
2829 
2830 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_client_key_exchange(mbedtls_ssl_context * ssl)2831 static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
2832 {
2833     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2834 
2835     size_t header_len;
2836     size_t content_len;
2837     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2838         ssl->handshake->ciphersuite_info;
2839 
2840     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
2841 
2842 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
2843     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
2844     {
2845         /*
2846          * DHM key exchange -- send G^X mod P
2847          */
2848         content_len = mbedtls_dhm_get_len( &ssl->handshake->dhm_ctx );
2849 
2850         MBEDTLS_PUT_UINT16_BE( content_len, ssl->out_msg, 4 );
2851         header_len = 6;
2852 
2853         ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
2854                           (int) mbedtls_dhm_get_len( &ssl->handshake->dhm_ctx ),
2855                           &ssl->out_msg[header_len], content_len,
2856                           ssl->conf->f_rng, ssl->conf->p_rng );
2857         if( ret != 0 )
2858         {
2859             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
2860             return( ret );
2861         }
2862 
2863         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
2864         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
2865 
2866         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
2867                                   ssl->handshake->premaster,
2868                                   MBEDTLS_PREMASTER_SIZE,
2869                                   &ssl->handshake->pmslen,
2870                                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2871         {
2872             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
2873             return( ret );
2874         }
2875 
2876         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
2877     }
2878     else
2879 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
2880 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2881     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2882     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
2883     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2884     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2885         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
2886         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2887         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
2888     {
2889 #if defined(MBEDTLS_USE_PSA_CRYPTO)
2890         psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2891         psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
2892         psa_key_attributes_t key_attributes;
2893 
2894         mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2895 
2896         header_len = 4;
2897 
2898         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Perform PSA-based ECDH computation." ) );
2899 
2900         /*
2901          * Generate EC private key for ECDHE exchange.
2902          */
2903 
2904         /* The master secret is obtained from the shared ECDH secret by
2905          * applying the TLS 1.2 PRF with a specific salt and label. While
2906          * the PSA Crypto API encourages combining key agreement schemes
2907          * such as ECDH with fixed KDFs such as TLS 1.2 PRF, it does not
2908          * yet support the provisioning of salt + label to the KDF.
2909          * For the time being, we therefore need to split the computation
2910          * of the ECDH secret and the application of the TLS 1.2 PRF. */
2911         key_attributes = psa_key_attributes_init();
2912         psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
2913         psa_set_key_algorithm( &key_attributes, PSA_ALG_ECDH );
2914         psa_set_key_type( &key_attributes, handshake->ecdh_psa_type );
2915         psa_set_key_bits( &key_attributes, handshake->ecdh_bits );
2916 
2917         /* Generate ECDH private key. */
2918         status = psa_generate_key( &key_attributes,
2919                                    &handshake->ecdh_psa_privkey );
2920         if( status != PSA_SUCCESS )
2921             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2922 
2923         /* Export the public part of the ECDH private key from PSA.
2924          * The export format is an ECPoint structure as expected by TLS,
2925          * but we just need to add a length byte before that. */
2926         unsigned char *own_pubkey = ssl->out_msg + header_len + 1;
2927         unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2928         size_t own_pubkey_max_len = (size_t)( end - own_pubkey );
2929         size_t own_pubkey_len;
2930 
2931         status = psa_export_public_key( handshake->ecdh_psa_privkey,
2932                                         own_pubkey, own_pubkey_max_len,
2933                                         &own_pubkey_len );
2934         if( status != PSA_SUCCESS )
2935         {
2936             psa_destroy_key( handshake->ecdh_psa_privkey );
2937             handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
2938             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2939         }
2940 
2941         ssl->out_msg[header_len] = (unsigned char) own_pubkey_len;
2942         content_len = own_pubkey_len + 1;
2943 
2944         /* The ECDH secret is the premaster secret used for key derivation. */
2945 
2946         /* Compute ECDH shared secret. */
2947         status = psa_raw_key_agreement( PSA_ALG_ECDH,
2948                                         handshake->ecdh_psa_privkey,
2949                                         handshake->ecdh_psa_peerkey,
2950                                         handshake->ecdh_psa_peerkey_len,
2951                                         ssl->handshake->premaster,
2952                                         sizeof( ssl->handshake->premaster ),
2953                                         &ssl->handshake->pmslen );
2954 
2955         destruction_status = psa_destroy_key( handshake->ecdh_psa_privkey );
2956         handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
2957 
2958         if( status != PSA_SUCCESS || destruction_status != PSA_SUCCESS )
2959             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2960 #else
2961         /*
2962          * ECDH key exchange -- send client public value
2963          */
2964         header_len = 4;
2965 
2966 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2967         if( ssl->handshake->ecrs_enabled )
2968         {
2969             if( ssl->handshake->ecrs_state == ssl_ecrs_cke_ecdh_calc_secret )
2970                 goto ecdh_calc_secret;
2971 
2972             mbedtls_ecdh_enable_restart( &ssl->handshake->ecdh_ctx );
2973         }
2974 #endif
2975 
2976         ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
2977                                 &content_len,
2978                                 &ssl->out_msg[header_len], 1000,
2979                                 ssl->conf->f_rng, ssl->conf->p_rng );
2980         if( ret != 0 )
2981         {
2982             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
2983 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2984             if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2985                 ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
2986 #endif
2987             return( ret );
2988         }
2989 
2990         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
2991                                 MBEDTLS_DEBUG_ECDH_Q );
2992 
2993 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2994         if( ssl->handshake->ecrs_enabled )
2995         {
2996             ssl->handshake->ecrs_n = content_len;
2997             ssl->handshake->ecrs_state = ssl_ecrs_cke_ecdh_calc_secret;
2998         }
2999 
3000 ecdh_calc_secret:
3001         if( ssl->handshake->ecrs_enabled )
3002             content_len = ssl->handshake->ecrs_n;
3003 #endif
3004         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
3005                                   &ssl->handshake->pmslen,
3006                                   ssl->handshake->premaster,
3007                                   MBEDTLS_MPI_MAX_SIZE,
3008                                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3009         {
3010             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
3011 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3012             if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
3013                 ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
3014 #endif
3015             return( ret );
3016         }
3017 
3018         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
3019                                 MBEDTLS_DEBUG_ECDH_Z );
3020 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3021     }
3022     else
3023 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3024           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
3025           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
3026           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3027 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
3028     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3029     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
3030     {
3031         psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3032         psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
3033         psa_key_attributes_t key_attributes;
3034 
3035         mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3036 
3037         /*
3038          * opaque psk_identity<0..2^16-1>;
3039          */
3040         if( mbedtls_ssl_conf_has_static_psk( ssl->conf ) == 0 )
3041             /* We don't offer PSK suites if we don't have a PSK,
3042              * and we check that the server's choice is among the
3043              * ciphersuites we offered, so this should never happen. */
3044             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3045 
3046         /* uint16 to store content length */
3047         const size_t content_len_size = 2;
3048 
3049         header_len = 4;
3050 
3051         if( header_len + content_len_size + ssl->conf->psk_identity_len
3052                     > MBEDTLS_SSL_OUT_CONTENT_LEN )
3053         {
3054             MBEDTLS_SSL_DEBUG_MSG( 1,
3055                 ( "psk identity too long or SSL buffer too short" ) );
3056             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3057         }
3058 
3059         unsigned char *p = ssl->out_msg + header_len;
3060 
3061         *p++ = MBEDTLS_BYTE_1( ssl->conf->psk_identity_len );
3062         *p++ = MBEDTLS_BYTE_0( ssl->conf->psk_identity_len );
3063         header_len += content_len_size;
3064 
3065         memcpy( p, ssl->conf->psk_identity,
3066                 ssl->conf->psk_identity_len );
3067         p += ssl->conf->psk_identity_len;
3068 
3069         header_len += ssl->conf->psk_identity_len;
3070 
3071         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Perform PSA-based ECDH computation." ) );
3072 
3073         /*
3074          * Generate EC private key for ECDHE exchange.
3075          */
3076 
3077         /* The master secret is obtained from the shared ECDH secret by
3078          * applying the TLS 1.2 PRF with a specific salt and label. While
3079          * the PSA Crypto API encourages combining key agreement schemes
3080          * such as ECDH with fixed KDFs such as TLS 1.2 PRF, it does not
3081          * yet support the provisioning of salt + label to the KDF.
3082          * For the time being, we therefore need to split the computation
3083          * of the ECDH secret and the application of the TLS 1.2 PRF. */
3084         key_attributes = psa_key_attributes_init();
3085         psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
3086         psa_set_key_algorithm( &key_attributes, PSA_ALG_ECDH );
3087         psa_set_key_type( &key_attributes, handshake->ecdh_psa_type );
3088         psa_set_key_bits( &key_attributes, handshake->ecdh_bits );
3089 
3090         /* Generate ECDH private key. */
3091         status = psa_generate_key( &key_attributes,
3092                                    &handshake->ecdh_psa_privkey );
3093         if( status != PSA_SUCCESS )
3094             return( psa_ssl_status_to_mbedtls( status ) );
3095 
3096         /* Export the public part of the ECDH private key from PSA.
3097          * The export format is an ECPoint structure as expected by TLS,
3098          * but we just need to add a length byte before that. */
3099         unsigned char *own_pubkey = p + 1;
3100         unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
3101         size_t own_pubkey_max_len = (size_t)( end - own_pubkey );
3102         size_t own_pubkey_len = 0;
3103 
3104         status = psa_export_public_key( handshake->ecdh_psa_privkey,
3105                                         own_pubkey, own_pubkey_max_len,
3106                                         &own_pubkey_len );
3107         if( status != PSA_SUCCESS )
3108         {
3109             psa_destroy_key( handshake->ecdh_psa_privkey );
3110             handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3111             return( psa_ssl_status_to_mbedtls( status ) );
3112         }
3113 
3114         *p = (unsigned char) own_pubkey_len;
3115         content_len = own_pubkey_len + 1;
3116 
3117         /* As RFC 5489 section 2, the premaster secret is formed as follows:
3118          * - a uint16 containing the length (in octets) of the ECDH computation
3119          * - the octet string produced by the ECDH computation
3120          * - a uint16 containing the length (in octets) of the PSK
3121          * - the PSK itself
3122          */
3123         unsigned char *pms = ssl->handshake->premaster;
3124         const unsigned char* const pms_end = pms +
3125                                 sizeof( ssl->handshake->premaster );
3126         /* uint16 to store length (in octets) of the ECDH computation */
3127         const size_t zlen_size = 2;
3128         size_t zlen = 0;
3129 
3130         /* Perform ECDH computation after the uint16 reserved for the length */
3131         status = psa_raw_key_agreement( PSA_ALG_ECDH,
3132                                         handshake->ecdh_psa_privkey,
3133                                         handshake->ecdh_psa_peerkey,
3134                                         handshake->ecdh_psa_peerkey_len,
3135                                         pms + zlen_size,
3136                                         pms_end - ( pms + zlen_size ),
3137                                         &zlen );
3138 
3139         destruction_status = psa_destroy_key( handshake->ecdh_psa_privkey );
3140         handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3141 
3142         if( status != PSA_SUCCESS )
3143             return( psa_ssl_status_to_mbedtls( status ) );
3144         else if( destruction_status != PSA_SUCCESS )
3145             return( psa_ssl_status_to_mbedtls( destruction_status ) );
3146 
3147         /* Write the ECDH computation length before the ECDH computation */
3148         MBEDTLS_PUT_UINT16_BE( zlen, pms, 0 );
3149         pms += zlen_size + zlen;
3150     }
3151     else
3152 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
3153           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
3154 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
3155     if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
3156     {
3157         /*
3158          * opaque psk_identity<0..2^16-1>;
3159          */
3160         if( mbedtls_ssl_conf_has_static_psk( ssl->conf ) == 0 )
3161         {
3162             /* We don't offer PSK suites if we don't have a PSK,
3163              * and we check that the server's choice is among the
3164              * ciphersuites we offered, so this should never happen. */
3165             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3166         }
3167 
3168         header_len = 4;
3169         content_len = ssl->conf->psk_identity_len;
3170 
3171         if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
3172         {
3173             MBEDTLS_SSL_DEBUG_MSG( 1,
3174                 ( "psk identity too long or SSL buffer too short" ) );
3175             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3176         }
3177 
3178         ssl->out_msg[header_len++] = MBEDTLS_BYTE_1( content_len );
3179         ssl->out_msg[header_len++] = MBEDTLS_BYTE_0( content_len );
3180 
3181         memcpy( ssl->out_msg + header_len,
3182                 ssl->conf->psk_identity,
3183                 ssl->conf->psk_identity_len );
3184         header_len += ssl->conf->psk_identity_len;
3185 
3186 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
3187         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
3188         {
3189             content_len = 0;
3190         }
3191         else
3192 #endif
3193 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3194         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
3195         {
3196             if( ( ret = ssl_write_encrypted_pms( ssl, header_len,
3197                                                  &content_len, 2 ) ) != 0 )
3198                 return( ret );
3199         }
3200         else
3201 #endif
3202 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3203         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
3204         {
3205             /*
3206              * ClientDiffieHellmanPublic public (DHM send G^X mod P)
3207              */
3208             content_len = mbedtls_dhm_get_len( &ssl->handshake->dhm_ctx );
3209 
3210             if( header_len + 2 + content_len >
3211                 MBEDTLS_SSL_OUT_CONTENT_LEN )
3212             {
3213                 MBEDTLS_SSL_DEBUG_MSG( 1,
3214                     ( "psk identity or DHM size too long or SSL buffer too short" ) );
3215                 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3216             }
3217 
3218             ssl->out_msg[header_len++] = MBEDTLS_BYTE_1( content_len );
3219             ssl->out_msg[header_len++] = MBEDTLS_BYTE_0( content_len );
3220 
3221             ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
3222                     (int) mbedtls_dhm_get_len( &ssl->handshake->dhm_ctx ),
3223                     &ssl->out_msg[header_len], content_len,
3224                     ssl->conf->f_rng, ssl->conf->p_rng );
3225             if( ret != 0 )
3226             {
3227                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
3228                 return( ret );
3229             }
3230 
3231 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3232             unsigned char *pms = ssl->handshake->premaster;
3233             unsigned char *pms_end = pms + sizeof( ssl->handshake->premaster );
3234             size_t pms_len;
3235 
3236             /* Write length only when we know the actual value */
3237             if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
3238                                           pms + 2, pms_end - ( pms + 2 ), &pms_len,
3239                                           ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3240             {
3241                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
3242                 return( ret );
3243             }
3244             MBEDTLS_PUT_UINT16_BE( pms_len, pms, 0 );
3245             pms += 2 + pms_len;
3246 
3247             MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
3248 #endif
3249         }
3250         else
3251 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3252 #if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
3253     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3254         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
3255         {
3256             /*
3257              * ClientECDiffieHellmanPublic public;
3258              */
3259             ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
3260                     &content_len,
3261                     &ssl->out_msg[header_len],
3262                     MBEDTLS_SSL_OUT_CONTENT_LEN - header_len,
3263                     ssl->conf->f_rng, ssl->conf->p_rng );
3264             if( ret != 0 )
3265             {
3266                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
3267                 return( ret );
3268             }
3269 
3270             MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
3271                                     MBEDTLS_DEBUG_ECDH_Q );
3272         }
3273         else
3274 #endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
3275         {
3276             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3277             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3278         }
3279 
3280 #if !defined(MBEDTLS_USE_PSA_CRYPTO)
3281         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
3282                         ciphersuite_info->key_exchange ) ) != 0 )
3283         {
3284             MBEDTLS_SSL_DEBUG_RET( 1,
3285                     "mbedtls_ssl_psk_derive_premaster", ret );
3286             return( ret );
3287         }
3288 #endif /* !MBEDTLS_USE_PSA_CRYPTO */
3289     }
3290     else
3291 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
3292 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
3293     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
3294     {
3295         header_len = 4;
3296         if( ( ret = ssl_write_encrypted_pms( ssl, header_len,
3297                                              &content_len, 0 ) ) != 0 )
3298             return( ret );
3299     }
3300     else
3301 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
3302 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3303     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
3304     {
3305         header_len = 4;
3306 
3307 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3308         unsigned char *out_p = ssl->out_msg + header_len;
3309         unsigned char *end_p = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN -
3310                                header_len;
3311         ret = mbedtls_psa_ecjpake_write_round( &ssl->handshake->psa_pake_ctx,
3312                                     out_p, end_p - out_p, &content_len,
3313                                     MBEDTLS_ECJPAKE_ROUND_TWO );
3314         if ( ret != 0 )
3315         {
3316             psa_destroy_key( ssl->handshake->psa_pake_password );
3317             psa_pake_abort( &ssl->handshake->psa_pake_ctx );
3318             MBEDTLS_SSL_DEBUG_RET( 1 , "psa_pake_output", ret );
3319             return( ret );
3320         }
3321 #else
3322         ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
3323                 ssl->out_msg + header_len,
3324                 MBEDTLS_SSL_OUT_CONTENT_LEN - header_len,
3325                 &content_len,
3326                 ssl->conf->f_rng, ssl->conf->p_rng );
3327         if( ret != 0 )
3328         {
3329             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
3330             return( ret );
3331         }
3332 
3333         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
3334                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
3335                 ssl->conf->f_rng, ssl->conf->p_rng );
3336         if( ret != 0 )
3337         {
3338             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
3339             return( ret );
3340         }
3341 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3342     }
3343     else
3344 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
3345     {
3346         ((void) ciphersuite_info);
3347         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3348         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3349     }
3350 
3351     ssl->out_msglen  = header_len + content_len;
3352     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3353     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
3354 
3355     ssl->state++;
3356 
3357     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
3358     {
3359         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
3360         return( ret );
3361     }
3362 
3363     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
3364 
3365     return( 0 );
3366 }
3367 
3368 #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
3369 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_certificate_verify(mbedtls_ssl_context * ssl)3370 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
3371 {
3372     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3373         ssl->handshake->ciphersuite_info;
3374     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3375 
3376     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
3377 
3378     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
3379     {
3380         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
3381         return( ret );
3382     }
3383 
3384     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
3385     {
3386         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3387         ssl->state++;
3388         return( 0 );
3389     }
3390 
3391     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3392     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3393 }
3394 #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
3395 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_write_certificate_verify(mbedtls_ssl_context * ssl)3396 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
3397 {
3398     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3399     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3400         ssl->handshake->ciphersuite_info;
3401     size_t n = 0, offset = 0;
3402     unsigned char hash[48];
3403     unsigned char *hash_start = hash;
3404     mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
3405     size_t hashlen;
3406     void *rs_ctx = NULL;
3407 #if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3408     size_t out_buf_len = ssl->out_buf_len - ( ssl->out_msg - ssl->out_buf );
3409 #else
3410     size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN - ( ssl->out_msg - ssl->out_buf );
3411 #endif
3412 
3413     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
3414 
3415 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3416     if( ssl->handshake->ecrs_enabled &&
3417         ssl->handshake->ecrs_state == ssl_ecrs_crt_vrfy_sign )
3418     {
3419         goto sign;
3420     }
3421 #endif
3422 
3423     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
3424     {
3425         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
3426         return( ret );
3427     }
3428 
3429     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
3430     {
3431         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3432         ssl->state++;
3433         return( 0 );
3434     }
3435 
3436     if( ssl->handshake->client_auth == 0 ||
3437         mbedtls_ssl_own_cert( ssl ) == NULL )
3438     {
3439         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3440         ssl->state++;
3441         return( 0 );
3442     }
3443 
3444     if( mbedtls_ssl_own_key( ssl ) == NULL )
3445     {
3446         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
3447         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
3448     }
3449 
3450     /*
3451      * Make a signature of the handshake digests
3452      */
3453 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3454     if( ssl->handshake->ecrs_enabled )
3455         ssl->handshake->ecrs_state = ssl_ecrs_crt_vrfy_sign;
3456 
3457 sign:
3458 #endif
3459 
3460     ssl->handshake->calc_verify( ssl, hash, &hashlen );
3461 
3462     /*
3463      * digitally-signed struct {
3464      *     opaque handshake_messages[handshake_messages_length];
3465      * };
3466      *
3467      * Taking shortcut here. We assume that the server always allows the
3468      * PRF Hash function and has sent it in the allowed signature
3469      * algorithms list received in the Certificate Request message.
3470      *
3471      * Until we encounter a server that does not, we will take this
3472      * shortcut.
3473      *
3474      * Reason: Otherwise we should have running hashes for SHA512 and
3475      *         SHA224 in order to satisfy 'weird' needs from the server
3476      *         side.
3477      */
3478     if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
3479     {
3480         md_alg = MBEDTLS_MD_SHA384;
3481         ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
3482     }
3483     else
3484     {
3485         md_alg = MBEDTLS_MD_SHA256;
3486         ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
3487     }
3488     ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
3489 
3490     /* Info from md_alg will be used instead */
3491     hashlen = 0;
3492     offset = 2;
3493 
3494 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3495     if( ssl->handshake->ecrs_enabled )
3496         rs_ctx = &ssl->handshake->ecrs_ctx.pk;
3497 #endif
3498 
3499     if( ( ret = mbedtls_pk_sign_restartable( mbedtls_ssl_own_key( ssl ),
3500                          md_alg, hash_start, hashlen,
3501                          ssl->out_msg + 6 + offset,
3502                          out_buf_len - 6 - offset,
3503                          &n,
3504                          ssl->conf->f_rng, ssl->conf->p_rng, rs_ctx ) ) != 0 )
3505     {
3506         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
3507 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3508         if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
3509             ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
3510 #endif
3511         return( ret );
3512     }
3513 
3514     MBEDTLS_PUT_UINT16_BE( n, ssl->out_msg, offset + 4 );
3515 
3516     ssl->out_msglen  = 6 + n + offset;
3517     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3518     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
3519 
3520     ssl->state++;
3521 
3522     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
3523     {
3524         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
3525         return( ret );
3526     }
3527 
3528     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
3529 
3530     return( ret );
3531 }
3532 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
3533 
3534 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3535 MBEDTLS_CHECK_RETURN_CRITICAL
ssl_parse_new_session_ticket(mbedtls_ssl_context * ssl)3536 static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
3537 {
3538     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3539     uint32_t lifetime;
3540     size_t ticket_len;
3541     unsigned char *ticket;
3542     const unsigned char *msg;
3543 
3544     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
3545 
3546     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
3547     {
3548         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
3549         return( ret );
3550     }
3551 
3552     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
3553     {
3554         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3555         mbedtls_ssl_send_alert_message(
3556             ssl,
3557             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3558             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
3559         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3560     }
3561 
3562     /*
3563      * struct {
3564      *     uint32 ticket_lifetime_hint;
3565      *     opaque ticket<0..2^16-1>;
3566      * } NewSessionTicket;
3567      *
3568      * 0  .  3   ticket_lifetime_hint
3569      * 4  .  5   ticket_len (n)
3570      * 6  .  5+n ticket content
3571      */
3572     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
3573         ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
3574     {
3575         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3576         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3577                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3578         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
3579     }
3580 
3581     msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
3582 
3583     lifetime = ( ((uint32_t) msg[0]) << 24 ) | ( msg[1] << 16 ) |
3584                ( msg[2] << 8 ) | ( msg[3] );
3585 
3586     ticket_len = ( msg[4] << 8 ) | ( msg[5] );
3587 
3588     if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
3589     {
3590         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3591         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3592                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3593         return( MBEDTLS_ERR_SSL_DECODE_ERROR );
3594     }
3595 
3596     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %" MBEDTLS_PRINTF_SIZET, ticket_len ) );
3597 
3598     /* We're not waiting for a NewSessionTicket message any more */
3599     ssl->handshake->new_session_ticket = 0;
3600     ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
3601 
3602     /*
3603      * Zero-length ticket means the server changed his mind and doesn't want
3604      * to send a ticket after all, so just forget it
3605      */
3606     if( ticket_len == 0 )
3607         return( 0 );
3608 
3609     if( ssl->session != NULL && ssl->session->ticket != NULL )
3610     {
3611         mbedtls_platform_zeroize( ssl->session->ticket,
3612                                   ssl->session->ticket_len );
3613         mbedtls_free( ssl->session->ticket );
3614         ssl->session->ticket = NULL;
3615         ssl->session->ticket_len = 0;
3616     }
3617 
3618     mbedtls_platform_zeroize( ssl->session_negotiate->ticket,
3619                               ssl->session_negotiate->ticket_len );
3620     mbedtls_free( ssl->session_negotiate->ticket );
3621     ssl->session_negotiate->ticket = NULL;
3622     ssl->session_negotiate->ticket_len = 0;
3623 
3624     if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
3625     {
3626         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
3627         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3628                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
3629         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
3630     }
3631 
3632     memcpy( ticket, msg + 6, ticket_len );
3633 
3634     ssl->session_negotiate->ticket = ticket;
3635     ssl->session_negotiate->ticket_len = ticket_len;
3636     ssl->session_negotiate->ticket_lifetime = lifetime;
3637 
3638     /*
3639      * RFC 5077 section 3.4:
3640      * "If the client receives a session ticket from the server, then it
3641      * discards any Session ID that was sent in the ServerHello."
3642      */
3643     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
3644     ssl->session_negotiate->id_len = 0;
3645 
3646     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
3647 
3648     return( 0 );
3649 }
3650 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3651 
3652 /*
3653  * SSL handshake -- client side -- single step
3654  */
mbedtls_ssl_handshake_client_step(mbedtls_ssl_context * ssl)3655 int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
3656 {
3657     int ret = 0;
3658 
3659     /* Change state now, so that it is right in mbedtls_ssl_read_record(), used
3660      * by DTLS for dropping out-of-sequence ChangeCipherSpec records */
3661 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3662     if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
3663         ssl->handshake->new_session_ticket != 0 )
3664     {
3665         ssl->state = MBEDTLS_SSL_NEW_SESSION_TICKET;
3666     }
3667 #endif
3668 
3669     switch( ssl->state )
3670     {
3671         case MBEDTLS_SSL_HELLO_REQUEST:
3672             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
3673             break;
3674 
3675        /*
3676         *  ==>   ClientHello
3677         */
3678        case MBEDTLS_SSL_CLIENT_HELLO:
3679            ret = mbedtls_ssl_write_client_hello( ssl );
3680            break;
3681 
3682        /*
3683         *  <==   ServerHello
3684         *        Certificate
3685         *      ( ServerKeyExchange  )
3686         *      ( CertificateRequest )
3687         *        ServerHelloDone
3688         */
3689        case MBEDTLS_SSL_SERVER_HELLO:
3690            ret = ssl_parse_server_hello( ssl );
3691            break;
3692 
3693        case MBEDTLS_SSL_SERVER_CERTIFICATE:
3694            ret = mbedtls_ssl_parse_certificate( ssl );
3695            break;
3696 
3697        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
3698            ret = ssl_parse_server_key_exchange( ssl );
3699            break;
3700 
3701        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
3702            ret = ssl_parse_certificate_request( ssl );
3703            break;
3704 
3705        case MBEDTLS_SSL_SERVER_HELLO_DONE:
3706            ret = ssl_parse_server_hello_done( ssl );
3707            break;
3708 
3709        /*
3710         *  ==> ( Certificate/Alert  )
3711         *        ClientKeyExchange
3712         *      ( CertificateVerify  )
3713         *        ChangeCipherSpec
3714         *        Finished
3715         */
3716        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
3717            ret = mbedtls_ssl_write_certificate( ssl );
3718            break;
3719 
3720        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
3721            ret = ssl_write_client_key_exchange( ssl );
3722            break;
3723 
3724        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
3725            ret = ssl_write_certificate_verify( ssl );
3726            break;
3727 
3728        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
3729            ret = mbedtls_ssl_write_change_cipher_spec( ssl );
3730            break;
3731 
3732        case MBEDTLS_SSL_CLIENT_FINISHED:
3733            ret = mbedtls_ssl_write_finished( ssl );
3734            break;
3735 
3736        /*
3737         *  <==   ( NewSessionTicket )
3738         *        ChangeCipherSpec
3739         *        Finished
3740         */
3741 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3742        case MBEDTLS_SSL_NEW_SESSION_TICKET:
3743            ret = ssl_parse_new_session_ticket( ssl );
3744            break;
3745 #endif
3746 
3747        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
3748            ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
3749            break;
3750 
3751        case MBEDTLS_SSL_SERVER_FINISHED:
3752            ret = mbedtls_ssl_parse_finished( ssl );
3753            break;
3754 
3755        case MBEDTLS_SSL_FLUSH_BUFFERS:
3756            MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
3757            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3758            break;
3759 
3760        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
3761            mbedtls_ssl_handshake_wrapup( ssl );
3762            break;
3763 
3764        default:
3765            MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
3766            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3767    }
3768 
3769     return( ret );
3770 }
3771 
3772 #endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_PROTO_TLS1_2 */
3773