1 /*
2  *  SSLv3/TLSv1 server-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_SRV_C)
23 
24 #if defined(MBEDTLS_PLATFORM_C)
25 #include "mbedtls/platform.h"
26 #else
27 #include <stdlib.h>
28 #define mbedtls_calloc    calloc
29 #define mbedtls_free      free
30 #endif
31 
32 #include "mbedtls/ssl.h"
33 #include "mbedtls/ssl_internal.h"
34 #include "mbedtls/debug.h"
35 #include "mbedtls/error.h"
36 #include "mbedtls/platform_util.h"
37 #include "constant_time_internal.h"
38 #include "mbedtls/constant_time.h"
39 
40 #include <string.h>
41 
42 #if defined(MBEDTLS_ECP_C)
43 #include "mbedtls/ecp.h"
44 #endif
45 
46 #if defined(MBEDTLS_HAVE_TIME)
47 #include "mbedtls/platform_time.h"
48 #endif
49 
50 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
mbedtls_ssl_set_client_transport_id(mbedtls_ssl_context * ssl,const unsigned char * info,size_t ilen)51 int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl,
52                                  const unsigned char *info,
53                                  size_t ilen )
54 {
55     if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER )
56         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
57 
58     mbedtls_free( ssl->cli_id );
59 
60     if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL )
61         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
62 
63     memcpy( ssl->cli_id, info, ilen );
64     ssl->cli_id_len = ilen;
65 
66     return( 0 );
67 }
68 
mbedtls_ssl_conf_dtls_cookies(mbedtls_ssl_config * conf,mbedtls_ssl_cookie_write_t * f_cookie_write,mbedtls_ssl_cookie_check_t * f_cookie_check,void * p_cookie)69 void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf,
70                            mbedtls_ssl_cookie_write_t *f_cookie_write,
71                            mbedtls_ssl_cookie_check_t *f_cookie_check,
72                            void *p_cookie )
73 {
74     conf->f_cookie_write = f_cookie_write;
75     conf->f_cookie_check = f_cookie_check;
76     conf->p_cookie       = p_cookie;
77 }
78 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
79 
80 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
ssl_parse_servername_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)81 static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl,
82                                      const unsigned char *buf,
83                                      size_t len )
84 {
85     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
86     size_t servername_list_size, hostname_len;
87     const unsigned char *p;
88 
89     MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) );
90 
91     if( len < 2 )
92     {
93         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
94         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
95                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
96         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
97     }
98     servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
99     if( servername_list_size + 2 != len )
100     {
101         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
102         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
103                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
104         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
105     }
106 
107     p = buf + 2;
108     while( servername_list_size > 2 )
109     {
110         hostname_len = ( ( p[1] << 8 ) | p[2] );
111         if( hostname_len + 3 > servername_list_size )
112         {
113             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
114             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
115                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
116             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
117         }
118 
119         if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME )
120         {
121             ret = ssl->conf->f_sni( ssl->conf->p_sni,
122                                     ssl, p + 3, hostname_len );
123             if( ret != 0 )
124             {
125                 MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret );
126                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
127                         MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME );
128                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
129             }
130             return( 0 );
131         }
132 
133         servername_list_size -= hostname_len + 3;
134         p += hostname_len + 3;
135     }
136 
137     if( servername_list_size != 0 )
138     {
139         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
140         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
141                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
142         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
143     }
144 
145     return( 0 );
146 }
147 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
148 
149 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
ssl_conf_has_psk_or_cb(mbedtls_ssl_config const * conf)150 static int ssl_conf_has_psk_or_cb( mbedtls_ssl_config const *conf )
151 {
152     if( conf->f_psk != NULL )
153         return( 1 );
154 
155     if( conf->psk_identity_len == 0 || conf->psk_identity == NULL )
156         return( 0 );
157 
158     if( conf->psk != NULL && conf->psk_len != 0 )
159         return( 1 );
160 
161 #if defined(MBEDTLS_USE_PSA_CRYPTO)
162     if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) )
163         return( 1 );
164 #endif /* MBEDTLS_USE_PSA_CRYPTO */
165 
166     return( 0 );
167 }
168 
169 #if defined(MBEDTLS_USE_PSA_CRYPTO)
ssl_use_opaque_psk(mbedtls_ssl_context const * ssl)170 static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl )
171 {
172     if( ssl->conf->f_psk != NULL )
173     {
174         /* If we've used a callback to select the PSK,
175          * the static configuration is irrelevant. */
176 
177         if( ! mbedtls_svc_key_id_is_null( ssl->handshake->psk_opaque ) )
178             return( 1 );
179 
180         return( 0 );
181     }
182 
183     if( ! mbedtls_svc_key_id_is_null( ssl->conf->psk_opaque ) )
184         return( 1 );
185 
186     return( 0 );
187 }
188 #endif /* MBEDTLS_USE_PSA_CRYPTO */
189 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
190 
ssl_parse_renegotiation_info(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)191 static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
192                                          const unsigned char *buf,
193                                          size_t len )
194 {
195 #if defined(MBEDTLS_SSL_RENEGOTIATION)
196     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
197     {
198         /* Check verify-data in constant-time. The length OTOH is no secret */
199         if( len    != 1 + ssl->verify_data_len ||
200             buf[0] !=     ssl->verify_data_len ||
201             mbedtls_ct_memcmp( buf + 1, ssl->peer_verify_data,
202                           ssl->verify_data_len ) != 0 )
203         {
204             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
205             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
206                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
207             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
208         }
209     }
210     else
211 #endif /* MBEDTLS_SSL_RENEGOTIATION */
212     {
213         if( len != 1 || buf[0] != 0x0 )
214         {
215             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
216             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
217                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
218             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
219         }
220 
221         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
222     }
223 
224     return( 0 );
225 }
226 
227 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
228     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
229 
230 /*
231  * Status of the implementation of signature-algorithms extension:
232  *
233  * Currently, we are only considering the signature-algorithm extension
234  * to pick a ciphersuite which allows us to send the ServerKeyExchange
235  * message with a signature-hash combination that the user allows.
236  *
237  * We do *not* check whether all certificates in our certificate
238  * chain are signed with an allowed signature-hash pair.
239  * This needs to be done at a later stage.
240  *
241  */
ssl_parse_signature_algorithms_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)242 static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl,
243                                                const unsigned char *buf,
244                                                size_t len )
245 {
246     size_t sig_alg_list_size;
247 
248     const unsigned char *p;
249     const unsigned char *end = buf + len;
250 
251     mbedtls_md_type_t md_cur;
252     mbedtls_pk_type_t sig_cur;
253 
254     if ( len < 2 ) {
255         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
256         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
257                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
258         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
259     }
260     sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
261     if( sig_alg_list_size + 2 != len ||
262         sig_alg_list_size % 2 != 0 )
263     {
264         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
265         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
266                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
267         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
268     }
269 
270     /* Currently we only guarantee signing the ServerKeyExchange message according
271      * to the constraints specified in this extension (see above), so it suffices
272      * to remember only one suitable hash for each possible signature algorithm.
273      *
274      * This will change when we also consider certificate signatures,
275      * in which case we will need to remember the whole signature-hash
276      * pair list from the extension.
277      */
278 
279     for( p = buf + 2; p < end; p += 2 )
280     {
281         /* Silently ignore unknown signature or hash algorithms. */
282 
283         if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE )
284         {
285             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext"
286                                         " unknown sig alg encoding %d", p[1] ) );
287             continue;
288         }
289 
290         /* Check if we support the hash the user proposes */
291         md_cur = mbedtls_ssl_md_alg_from_hash( p[0] );
292         if( md_cur == MBEDTLS_MD_NONE )
293         {
294             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
295                                         " unknown hash alg encoding %d", p[0] ) );
296             continue;
297         }
298 
299         if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 )
300         {
301             mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur );
302             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:"
303                                         " match sig %u and hash %u",
304                                         (unsigned) sig_cur, (unsigned) md_cur ) );
305         }
306         else
307         {
308             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: "
309                                         "hash alg %u not supported", (unsigned) md_cur ) );
310         }
311     }
312 
313     return( 0 );
314 }
315 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
316           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
317 
318 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
319     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_parse_supported_elliptic_curves(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)320 static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl,
321                                                 const unsigned char *buf,
322                                                 size_t len )
323 {
324     size_t list_size, our_size;
325     const unsigned char *p;
326     const mbedtls_ecp_curve_info *curve_info, **curves;
327 
328     if ( len < 2 ) {
329         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
330         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
331                                        MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
332         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
333     }
334     list_size = ( ( buf[0] << 8 ) | ( buf[1] ) );
335     if( list_size + 2 != len ||
336         list_size % 2 != 0 )
337     {
338         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
339         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
340                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
341         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
342     }
343 
344     /* Should never happen unless client duplicates the extension */
345     if( ssl->handshake->curves != NULL )
346     {
347         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
348         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
349                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
350         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
351     }
352 
353     /* Don't allow our peer to make us allocate too much memory,
354      * and leave room for a final 0 */
355     our_size = list_size / 2 + 1;
356     if( our_size > MBEDTLS_ECP_DP_MAX )
357         our_size = MBEDTLS_ECP_DP_MAX;
358 
359     if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL )
360     {
361         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
362                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
363         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
364     }
365 
366     ssl->handshake->curves = curves;
367 
368     p = buf + 2;
369     while( list_size > 0 && our_size > 1 )
370     {
371         curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] );
372 
373         if( curve_info != NULL )
374         {
375             *curves++ = curve_info;
376             our_size--;
377         }
378 
379         list_size -= 2;
380         p += 2;
381     }
382 
383     return( 0 );
384 }
385 
ssl_parse_supported_point_formats(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)386 static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl,
387                                               const unsigned char *buf,
388                                               size_t len )
389 {
390     size_t list_size;
391     const unsigned char *p;
392 
393     if( len == 0 || (size_t)( buf[0] + 1 ) != len )
394     {
395         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
396         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
397                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
398         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
399     }
400     list_size = buf[0];
401 
402     p = buf + 1;
403     while( list_size > 0 )
404     {
405         if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
406             p[0] == MBEDTLS_ECP_PF_COMPRESSED )
407         {
408 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
409             ssl->handshake->ecdh_ctx.point_format = p[0];
410 #endif
411 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
412             ssl->handshake->ecjpake_ctx.point_format = p[0];
413 #endif
414             MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
415             return( 0 );
416         }
417 
418         list_size--;
419         p++;
420     }
421 
422     return( 0 );
423 }
424 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
425           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
426 
427 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_parse_ecjpake_kkpp(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)428 static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
429                                    const unsigned char *buf,
430                                    size_t len )
431 {
432     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
433 
434     if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
435     {
436         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
437         return( 0 );
438     }
439 
440     if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
441                                                 buf, len ) ) != 0 )
442     {
443         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
444         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
445                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
446         return( ret );
447     }
448 
449     /* Only mark the extension as OK when we're sure it is */
450     ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK;
451 
452     return( 0 );
453 }
454 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
455 
456 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_parse_max_fragment_length_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)457 static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
458                                               const unsigned char *buf,
459                                               size_t len )
460 {
461     if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID )
462     {
463         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
464         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
465                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
466         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
467     }
468 
469     ssl->session_negotiate->mfl_code = buf[0];
470 
471     return( 0 );
472 }
473 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
474 
475 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
ssl_parse_cid_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)476 static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl,
477                               const unsigned char *buf,
478                               size_t len )
479 {
480     size_t peer_cid_len;
481 
482     /* CID extension only makes sense in DTLS */
483     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM )
484     {
485         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
486         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
487                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
488         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
489     }
490 
491     /*
492      * Quoting draft-ietf-tls-dtls-connection-id-05
493      * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
494      *
495      *   struct {
496      *      opaque cid<0..2^8-1>;
497      *   } ConnectionId;
498     */
499 
500     if( len < 1 )
501     {
502         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
503         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
504                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
505         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
506     }
507 
508     peer_cid_len = *buf++;
509     len--;
510 
511     if( len != peer_cid_len )
512     {
513         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
514         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
515                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
516         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
517     }
518 
519     /* Ignore CID if the user has disabled its use. */
520     if( ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED )
521     {
522         /* Leave ssl->handshake->cid_in_use in its default
523          * value of MBEDTLS_SSL_CID_DISABLED. */
524         MBEDTLS_SSL_DEBUG_MSG( 3, ( "Client sent CID extension, but CID disabled" ) );
525         return( 0 );
526     }
527 
528     if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX )
529     {
530         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
531         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
532                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
533         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
534     }
535 
536     ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
537     ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
538     memcpy( ssl->handshake->peer_cid, buf, peer_cid_len );
539 
540     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) );
541     MBEDTLS_SSL_DEBUG_BUF( 3, "Client CID", buf, peer_cid_len );
542 
543     return( 0 );
544 }
545 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
546 
547 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_parse_truncated_hmac_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)548 static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
549                                          const unsigned char *buf,
550                                          size_t len )
551 {
552     if( len != 0 )
553     {
554         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
555         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
556                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
557         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
558     }
559 
560     ((void) buf);
561 
562     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED )
563         ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
564 
565     return( 0 );
566 }
567 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
568 
569 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_parse_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)570 static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
571                                       const unsigned char *buf,
572                                       size_t len )
573 {
574     if( len != 0 )
575     {
576         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
577         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
578                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
579         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
580     }
581 
582     ((void) buf);
583 
584     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED &&
585         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
586     {
587         ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
588     }
589 
590     return( 0 );
591 }
592 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
593 
594 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_parse_extended_ms_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)595 static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
596                                       const unsigned char *buf,
597                                       size_t len )
598 {
599     if( len != 0 )
600     {
601         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
602         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
603                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
604         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
605     }
606 
607     ((void) buf);
608 
609     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED &&
610         ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
611     {
612         ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
613     }
614 
615     return( 0 );
616 }
617 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
618 
619 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_parse_session_ticket_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t len)620 static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
621                                          unsigned char *buf,
622                                          size_t len )
623 {
624     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
625     mbedtls_ssl_session session;
626 
627     mbedtls_ssl_session_init( &session );
628 
629     if( ssl->conf->f_ticket_parse == NULL ||
630         ssl->conf->f_ticket_write == NULL )
631     {
632         return( 0 );
633     }
634 
635     /* Remember the client asked us to send a new ticket */
636     ssl->handshake->new_session_ticket = 1;
637 
638     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %" MBEDTLS_PRINTF_SIZET, len ) );
639 
640     if( len == 0 )
641         return( 0 );
642 
643 #if defined(MBEDTLS_SSL_RENEGOTIATION)
644     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
645     {
646         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) );
647         return( 0 );
648     }
649 #endif /* MBEDTLS_SSL_RENEGOTIATION */
650 
651     /*
652      * Failures are ok: just ignore the ticket and proceed.
653      */
654     if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session,
655                                            buf, len ) ) != 0 )
656     {
657         mbedtls_ssl_session_free( &session );
658 
659         if( ret == MBEDTLS_ERR_SSL_INVALID_MAC )
660             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) );
661         else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED )
662             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) );
663         else
664             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret );
665 
666         return( 0 );
667     }
668 
669     /*
670      * Keep the session ID sent by the client, since we MUST send it back to
671      * inform them we're accepting the ticket  (RFC 5077 section 3.4)
672      */
673     session.id_len = ssl->session_negotiate->id_len;
674     memcpy( &session.id, ssl->session_negotiate->id, session.id_len );
675 
676     mbedtls_ssl_session_free( ssl->session_negotiate );
677     memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) );
678 
679     /* Zeroize instead of free as we copied the content */
680     mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) );
681 
682     MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) );
683 
684     ssl->handshake->resume = 1;
685 
686     /* Don't send a new ticket after all, this one is OK */
687     ssl->handshake->new_session_ticket = 0;
688 
689     return( 0 );
690 }
691 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
692 
693 #if defined(MBEDTLS_SSL_ALPN)
ssl_parse_alpn_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)694 static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
695                                const unsigned char *buf, size_t len )
696 {
697     size_t list_len, cur_len, ours_len;
698     const unsigned char *theirs, *start, *end;
699     const char **ours;
700 
701     /* If ALPN not configured, just ignore the extension */
702     if( ssl->conf->alpn_list == NULL )
703         return( 0 );
704 
705     /*
706      * opaque ProtocolName<1..2^8-1>;
707      *
708      * struct {
709      *     ProtocolName protocol_name_list<2..2^16-1>
710      * } ProtocolNameList;
711      */
712 
713     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
714     if( len < 4 )
715     {
716         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
717                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
718         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
719     }
720 
721     list_len = ( buf[0] << 8 ) | buf[1];
722     if( list_len != len - 2 )
723     {
724         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
725                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
726         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
727     }
728 
729     /*
730      * Validate peer's list (lengths)
731      */
732     start = buf + 2;
733     end = buf + len;
734     for( theirs = start; theirs != end; theirs += cur_len )
735     {
736         cur_len = *theirs++;
737 
738         /* Current identifier must fit in list */
739         if( cur_len > (size_t)( end - theirs ) )
740         {
741             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
742                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
743             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
744         }
745 
746         /* Empty strings MUST NOT be included */
747         if( cur_len == 0 )
748         {
749             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
750                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
751             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
752         }
753     }
754 
755     /*
756      * Use our order of preference
757      */
758     for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ )
759     {
760         ours_len = strlen( *ours );
761         for( theirs = start; theirs != end; theirs += cur_len )
762         {
763             cur_len = *theirs++;
764 
765             if( cur_len == ours_len &&
766                 memcmp( theirs, *ours, cur_len ) == 0 )
767             {
768                 ssl->alpn_chosen = *ours;
769                 return( 0 );
770             }
771         }
772     }
773 
774     /* If we get there, no match was found */
775     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
776                             MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL );
777     return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
778 }
779 #endif /* MBEDTLS_SSL_ALPN */
780 
781 #if defined(MBEDTLS_SSL_DTLS_SRTP)
ssl_parse_use_srtp_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)782 static int ssl_parse_use_srtp_ext( mbedtls_ssl_context *ssl,
783                                    const unsigned char *buf,
784                                    size_t len )
785 {
786     mbedtls_ssl_srtp_profile client_protection = MBEDTLS_TLS_SRTP_UNSET;
787     size_t i,j;
788     size_t profile_length;
789     uint16_t mki_length;
790     /*! 2 bytes for profile length and 1 byte for mki len */
791     const size_t size_of_lengths = 3;
792 
793     /* If use_srtp is not configured, just ignore the extension */
794     if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
795         ( ssl->conf->dtls_srtp_profile_list == NULL ) ||
796         ( ssl->conf->dtls_srtp_profile_list_len == 0 ) )
797     {
798         return( 0 );
799     }
800 
801     /* RFC5764 section 4.1.1
802      * uint8 SRTPProtectionProfile[2];
803      *
804      * struct {
805      *   SRTPProtectionProfiles SRTPProtectionProfiles;
806      *   opaque srtp_mki<0..255>;
807      * } UseSRTPData;
808 
809      * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
810      */
811 
812     /*
813      * Min length is 5: at least one protection profile(2 bytes)
814      *                  and length(2 bytes) + srtp_mki length(1 byte)
815      * Check here that we have at least 2 bytes of protection profiles length
816      * and one of srtp_mki length
817      */
818     if( len < size_of_lengths )
819     {
820         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
821                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
822         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
823     }
824 
825    ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
826 
827     /* first 2 bytes are protection profile length(in bytes) */
828     profile_length = ( buf[0] << 8 ) | buf[1];
829     buf += 2;
830 
831     /* The profile length cannot be bigger than input buffer size - lengths fields */
832     if( profile_length > len - size_of_lengths ||
833         profile_length % 2 != 0 ) /* profiles are 2 bytes long, so the length must be even */
834     {
835         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
836                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
837         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
838     }
839     /*
840      * parse the extension list values are defined in
841      * http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
842      */
843     for( j = 0; j < profile_length; j += 2 )
844     {
845         uint16_t protection_profile_value = buf[j] << 8 | buf[j + 1];
846         client_protection = mbedtls_ssl_check_srtp_profile_value( protection_profile_value );
847 
848         if( client_protection != MBEDTLS_TLS_SRTP_UNSET )
849         {
850             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found srtp profile: %s",
851                                     mbedtls_ssl_get_srtp_profile_as_string(
852                                             client_protection ) ) );
853         }
854         else
855         {
856             continue;
857         }
858         /* check if suggested profile is in our list */
859         for( i = 0; i < ssl->conf->dtls_srtp_profile_list_len; i++)
860         {
861             if( client_protection == ssl->conf->dtls_srtp_profile_list[i] )
862             {
863                 ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
864                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "selected srtp profile: %s",
865                                             mbedtls_ssl_get_srtp_profile_as_string(
866                                                     client_protection ) ) );
867                 break;
868             }
869         }
870         if( ssl->dtls_srtp_info.chosen_dtls_srtp_profile != MBEDTLS_TLS_SRTP_UNSET )
871             break;
872     }
873     buf += profile_length; /* buf points to the mki length */
874     mki_length = *buf;
875     buf++;
876 
877     if( mki_length > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH ||
878         mki_length + profile_length + size_of_lengths != len )
879     {
880         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
881                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
882         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
883     }
884 
885     /* Parse the mki only if present and mki is supported locally */
886     if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED &&
887           mki_length > 0 )
888     {
889         ssl->dtls_srtp_info.mki_len = mki_length;
890 
891         memcpy( ssl->dtls_srtp_info.mki_value, buf, mki_length );
892 
893         MBEDTLS_SSL_DEBUG_BUF( 3, "using mki",  ssl->dtls_srtp_info.mki_value,
894                                                 ssl->dtls_srtp_info.mki_len );
895     }
896 
897     return( 0 );
898 }
899 #endif /* MBEDTLS_SSL_DTLS_SRTP */
900 
901 /*
902  * Auxiliary functions for ServerHello parsing and related actions
903  */
904 
905 #if defined(MBEDTLS_X509_CRT_PARSE_C)
906 /*
907  * Return 0 if the given key uses one of the acceptable curves, -1 otherwise
908  */
909 #if defined(MBEDTLS_ECDSA_C)
ssl_check_key_curve(mbedtls_pk_context * pk,const mbedtls_ecp_curve_info ** curves)910 static int ssl_check_key_curve( mbedtls_pk_context *pk,
911                                 const mbedtls_ecp_curve_info **curves )
912 {
913     const mbedtls_ecp_curve_info **crv = curves;
914     mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp.id;
915 
916     while( *crv != NULL )
917     {
918         if( (*crv)->grp_id == grp_id )
919             return( 0 );
920         crv++;
921     }
922 
923     return( -1 );
924 }
925 #endif /* MBEDTLS_ECDSA_C */
926 
927 /*
928  * Try picking a certificate for this ciphersuite,
929  * return 0 on success and -1 on failure.
930  */
ssl_pick_cert(mbedtls_ssl_context * ssl,const mbedtls_ssl_ciphersuite_t * ciphersuite_info)931 static int ssl_pick_cert( mbedtls_ssl_context *ssl,
932                           const mbedtls_ssl_ciphersuite_t * ciphersuite_info )
933 {
934     mbedtls_ssl_key_cert *cur, *list, *fallback = NULL;
935     mbedtls_pk_type_t pk_alg =
936         mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
937     uint32_t flags;
938 
939 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
940     if( ssl->handshake->sni_key_cert != NULL )
941         list = ssl->handshake->sni_key_cert;
942     else
943 #endif
944         list = ssl->conf->key_cert;
945 
946     if( pk_alg == MBEDTLS_PK_NONE )
947         return( 0 );
948 
949     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite requires certificate" ) );
950 
951     if( list == NULL )
952     {
953         MBEDTLS_SSL_DEBUG_MSG( 3, ( "server has no certificate" ) );
954         return( -1 );
955     }
956 
957     for( cur = list; cur != NULL; cur = cur->next )
958     {
959         flags = 0;
960         MBEDTLS_SSL_DEBUG_CRT( 3, "candidate certificate chain, certificate",
961                           cur->cert );
962 
963         if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) )
964         {
965             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: key type" ) );
966             continue;
967         }
968 
969         /*
970          * This avoids sending the client a cert it'll reject based on
971          * keyUsage or other extensions.
972          *
973          * It also allows the user to provision different certificates for
974          * different uses based on keyUsage, eg if they want to avoid signing
975          * and decrypting with the same RSA key.
976          */
977         if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info,
978                                   MBEDTLS_SSL_IS_SERVER, &flags ) != 0 )
979         {
980             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: "
981                                 "(extended) key usage extension" ) );
982             continue;
983         }
984 
985 #if defined(MBEDTLS_ECDSA_C)
986         if( pk_alg == MBEDTLS_PK_ECDSA &&
987             ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 )
988         {
989             MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: elliptic curve" ) );
990             continue;
991         }
992 #endif
993 
994         /*
995          * Try to select a SHA-1 certificate for pre-1.2 clients, but still
996          * present them a SHA-higher cert rather than failing if it's the only
997          * one we got that satisfies the other conditions.
998          */
999         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 &&
1000             cur->cert->sig_md != MBEDTLS_MD_SHA1 )
1001         {
1002             if( fallback == NULL )
1003                 fallback = cur;
1004             {
1005                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate not preferred: "
1006                                     "sha-2 with pre-TLS 1.2 client" ) );
1007             continue;
1008             }
1009         }
1010 
1011         /* If we get there, we got a winner */
1012         break;
1013     }
1014 
1015     if( cur == NULL )
1016         cur = fallback;
1017 
1018     /* Do not update ssl->handshake->key_cert unless there is a match */
1019     if( cur != NULL )
1020     {
1021         ssl->handshake->key_cert = cur;
1022         MBEDTLS_SSL_DEBUG_CRT( 3, "selected certificate chain, certificate",
1023                           ssl->handshake->key_cert->cert );
1024         return( 0 );
1025     }
1026 
1027     return( -1 );
1028 }
1029 #endif /* MBEDTLS_X509_CRT_PARSE_C */
1030 
1031 /*
1032  * Check if a given ciphersuite is suitable for use with our config/keys/etc
1033  * Sets ciphersuite_info only if the suite matches.
1034  */
ssl_ciphersuite_match(mbedtls_ssl_context * ssl,int suite_id,const mbedtls_ssl_ciphersuite_t ** ciphersuite_info)1035 static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id,
1036                                   const mbedtls_ssl_ciphersuite_t **ciphersuite_info )
1037 {
1038     const mbedtls_ssl_ciphersuite_t *suite_info;
1039 
1040 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1041     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1042     mbedtls_pk_type_t sig_type;
1043 #endif
1044 
1045     suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id );
1046     if( suite_info == NULL )
1047     {
1048         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
1049         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
1050     }
1051 
1052     MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %#04x (%s)",
1053                                 (unsigned int) suite_id, suite_info->name ) );
1054 
1055     if( suite_info->min_minor_ver > ssl->minor_ver ||
1056         suite_info->max_minor_ver < ssl->minor_ver )
1057     {
1058         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: version" ) );
1059         return( 0 );
1060     }
1061 
1062 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1063     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
1064         ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
1065         return( 0 );
1066 #endif
1067 
1068 #if defined(MBEDTLS_ARC4_C)
1069     if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
1070             suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
1071     {
1072         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: rc4" ) );
1073         return( 0 );
1074     }
1075 #endif
1076 
1077 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1078     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
1079         ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 )
1080     {
1081         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: ecjpake "
1082                                     "not configured or ext missing" ) );
1083         return( 0 );
1084     }
1085 #endif
1086 
1087 
1088 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
1089     if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) &&
1090         ( ssl->handshake->curves == NULL ||
1091           ssl->handshake->curves[0] == NULL ) )
1092     {
1093         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
1094                             "no common elliptic curve" ) );
1095         return( 0 );
1096     }
1097 #endif
1098 
1099 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1100     /* If the ciphersuite requires a pre-shared key and we don't
1101      * have one, skip it now rather than failing later */
1102     if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&
1103         ssl_conf_has_psk_or_cb( ssl->conf ) == 0 )
1104     {
1105         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) );
1106         return( 0 );
1107     }
1108 #endif
1109 
1110 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1111     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1112     /* If the ciphersuite requires signing, check whether
1113      * a suitable hash algorithm is present. */
1114     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
1115     {
1116         sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info );
1117         if( sig_type != MBEDTLS_PK_NONE &&
1118             mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE )
1119         {
1120             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no suitable hash algorithm "
1121                                         "for signature algorithm %u", (unsigned) sig_type ) );
1122             return( 0 );
1123         }
1124     }
1125 
1126 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
1127           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1128 
1129 #if defined(MBEDTLS_X509_CRT_PARSE_C)
1130     /*
1131      * Final check: if ciphersuite requires us to have a
1132      * certificate/key of a particular type:
1133      * - select the appropriate certificate if we have one, or
1134      * - try the next ciphersuite if we don't
1135      * This must be done last since we modify the key_cert list.
1136      */
1137     if( ssl_pick_cert( ssl, suite_info ) != 0 )
1138     {
1139         MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: "
1140                             "no suitable certificate" ) );
1141         return( 0 );
1142     }
1143 #endif
1144 
1145     *ciphersuite_info = suite_info;
1146     return( 0 );
1147 }
1148 
1149 #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
ssl_parse_client_hello_v2(mbedtls_ssl_context * ssl)1150 static int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl )
1151 {
1152     int ret, got_common_suite;
1153     unsigned int i, j;
1154     size_t n;
1155     unsigned int ciph_len, sess_len, chal_len;
1156     unsigned char *buf, *p;
1157     const int *ciphersuites;
1158     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1159 
1160     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) );
1161 
1162 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1163     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
1164     {
1165         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) );
1166         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1167                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1168         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1169     }
1170 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1171 
1172     buf = ssl->in_hdr;
1173 
1174     MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, 5 );
1175 
1176     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d",
1177                    buf[2] ) );
1178     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d",
1179                    ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) );
1180     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]",
1181                    buf[3], buf[4] ) );
1182 
1183     /*
1184      * SSLv2 Client Hello
1185      *
1186      * Record layer:
1187      *     0  .   1   message length
1188      *
1189      * SSL layer:
1190      *     2  .   2   message type
1191      *     3  .   4   protocol version
1192      */
1193     if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO ||
1194         buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 )
1195     {
1196         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1197         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1198     }
1199 
1200     n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF;
1201 
1202     if( n < 17 || n > 512 )
1203     {
1204         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1205         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1206     }
1207 
1208     ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
1209     ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver )
1210                      ? buf[4]  : ssl->conf->max_minor_ver;
1211 
1212     if( ssl->minor_ver < ssl->conf->min_minor_ver )
1213     {
1214         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
1215                             " [%d:%d] < [%d:%d]",
1216                             ssl->major_ver, ssl->minor_ver,
1217                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
1218 
1219         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1220                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
1221         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
1222     }
1223 
1224     ssl->handshake->max_major_ver = buf[3];
1225     ssl->handshake->max_minor_ver = buf[4];
1226 
1227     if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 )
1228     {
1229         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
1230         return( ret );
1231     }
1232 
1233     ssl->handshake->update_checksum( ssl, buf + 2, n );
1234 
1235     buf = ssl->in_msg;
1236     n = ssl->in_left - 5;
1237 
1238     /*
1239      *    0  .   1   ciphersuitelist length
1240      *    2  .   3   session id length
1241      *    4  .   5   challenge length
1242      *    6  .  ..   ciphersuitelist
1243      *   ..  .  ..   session id
1244      *   ..  .  ..   challenge
1245      */
1246     MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, n );
1247 
1248     ciph_len = ( buf[0] << 8 ) | buf[1];
1249     sess_len = ( buf[2] << 8 ) | buf[3];
1250     chal_len = ( buf[4] << 8 ) | buf[5];
1251 
1252     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciph_len: %u, sess_len: %u, chal_len: %u",
1253                    ciph_len, sess_len, chal_len ) );
1254 
1255     /*
1256      * Make sure each parameter length is valid
1257      */
1258     if( ciph_len < 3 || ( ciph_len % 3 ) != 0 )
1259     {
1260         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1261         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1262     }
1263 
1264     if( sess_len > 32 )
1265     {
1266         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1267         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1268     }
1269 
1270     if( chal_len < 8 || chal_len > 32 )
1271     {
1272         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1273         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1274     }
1275 
1276     if( n != 6 + ciph_len + sess_len + chal_len )
1277     {
1278         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1279         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1280     }
1281 
1282     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
1283                    buf + 6, ciph_len );
1284     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id",
1285                    buf + 6 + ciph_len, sess_len );
1286     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, challenge",
1287                    buf + 6 + ciph_len + sess_len, chal_len );
1288 
1289     p = buf + 6 + ciph_len;
1290     ssl->session_negotiate->id_len = sess_len;
1291     memset( ssl->session_negotiate->id, 0,
1292             sizeof( ssl->session_negotiate->id ) );
1293     memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len );
1294 
1295     p += sess_len;
1296     memset( ssl->handshake->randbytes, 0, 64 );
1297     memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len );
1298 
1299     /*
1300      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1301      */
1302     for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
1303     {
1304         if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
1305         {
1306             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
1307 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1308             if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
1309             {
1310                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
1311                                     "during renegotiation" ) );
1312 
1313                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1314                                                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1315                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1316             }
1317 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1318             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
1319             break;
1320         }
1321     }
1322 
1323 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
1324     for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 )
1325     {
1326         if( p[0] == 0 &&
1327             MBEDTLS_GET_UINT16_BE(p, 1) != MBEDTLS_SSL_FALLBACK_SCSV_VALUE )
1328         {
1329             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received FALLBACK_SCSV" ) );
1330 
1331             if( ssl->minor_ver < ssl->conf->max_minor_ver )
1332             {
1333                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
1334 
1335                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1336                                         MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
1337 
1338                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1339             }
1340 
1341             break;
1342         }
1343     }
1344 #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
1345 
1346     got_common_suite = 0;
1347     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
1348     ciphersuite_info = NULL;
1349 #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
1350     for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
1351         for( i = 0; ciphersuites[i] != 0; i++ )
1352 #else
1353     for( i = 0; ciphersuites[i] != 0; i++ )
1354         for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 )
1355 #endif
1356         {
1357             if( p[0] != 0 ||
1358                 MBEDTLS_GET_UINT16_BE(p, 1) != ciphersuites[i] )
1359                 continue;
1360 
1361             got_common_suite = 1;
1362 
1363             if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
1364                                                &ciphersuite_info ) ) != 0 )
1365                 return( ret );
1366 
1367             if( ciphersuite_info != NULL )
1368                 goto have_ciphersuite_v2;
1369         }
1370 
1371     if( got_common_suite )
1372     {
1373         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
1374                             "but none of them usable" ) );
1375         return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
1376     }
1377     else
1378     {
1379         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
1380         return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
1381     }
1382 
1383 have_ciphersuite_v2:
1384     MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
1385 
1386     ssl->session_negotiate->ciphersuite = ciphersuites[i];
1387     ssl->handshake->ciphersuite_info = ciphersuite_info;
1388 
1389     /*
1390      * SSLv2 Client Hello relevant renegotiation security checks
1391      */
1392     if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1393         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
1394     {
1395         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
1396         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1397                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1398         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1399     }
1400 
1401     ssl->in_left = 0;
1402     ssl->state++;
1403 
1404     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) );
1405 
1406     return( 0 );
1407 }
1408 #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */
1409 
1410 /* This function doesn't alert on errors that happen early during
1411    ClientHello parsing because they might indicate that the client is
1412    not talking SSL/TLS at all and would not understand our alert. */
ssl_parse_client_hello(mbedtls_ssl_context * ssl)1413 static int ssl_parse_client_hello( mbedtls_ssl_context *ssl )
1414 {
1415     int ret, got_common_suite;
1416     size_t i, j;
1417     size_t ciph_offset, comp_offset, ext_offset;
1418     size_t msg_len, ciph_len, sess_len, comp_len, ext_len;
1419 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1420     size_t cookie_offset, cookie_len;
1421 #endif
1422     unsigned char *buf, *p, *ext;
1423 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1424     int renegotiation_info_seen = 0;
1425 #endif
1426     int handshake_failure = 0;
1427     const int *ciphersuites;
1428     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
1429     int major, minor;
1430 
1431     /* If there is no signature-algorithm extension present,
1432      * we need to fall back to the default values for allowed
1433      * signature-hash pairs. */
1434 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1435     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1436     int sig_hash_alg_ext_present = 0;
1437 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
1438           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1439 
1440     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) );
1441 
1442 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1443 read_record_header:
1444 #endif
1445     /*
1446      * If renegotiating, then the input was read with mbedtls_ssl_read_record(),
1447      * otherwise read it ourselves manually in order to support SSLv2
1448      * ClientHello, which doesn't use the same record layer format.
1449      */
1450 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1451     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
1452 #endif
1453     {
1454         if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 )
1455         {
1456             /* No alert on a read error. */
1457             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
1458             return( ret );
1459         }
1460     }
1461 
1462     buf = ssl->in_hdr;
1463 
1464 #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO)
1465 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1466     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM )
1467 #endif
1468         if( ( buf[0] & 0x80 ) != 0 )
1469             return( ssl_parse_client_hello_v2( ssl ) );
1470 #endif
1471 
1472     MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_in_hdr_len( ssl ) );
1473 
1474     /*
1475      * SSLv3/TLS Client Hello
1476      *
1477      * Record layer:
1478      *     0  .   0   message type
1479      *     1  .   2   protocol version
1480      *     3  .   11  DTLS: epoch + record sequence number
1481      *     3  .   4   message length
1482      */
1483     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d",
1484                    buf[0] ) );
1485 
1486     if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE )
1487     {
1488         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1489         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1490     }
1491 
1492     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d",
1493                    ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) );
1494 
1495     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, protocol version: [%d:%d]",
1496                    buf[1], buf[2] ) );
1497 
1498     mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 );
1499 
1500     /* According to RFC 5246 Appendix E.1, the version here is typically
1501      * "{03,00}, the lowest version number supported by the client, [or] the
1502      * value of ClientHello.client_version", so the only meaningful check here
1503      * is the major version shouldn't be less than 3 */
1504     if( major < MBEDTLS_SSL_MAJOR_VERSION_3 )
1505     {
1506         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1507         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1508     }
1509 
1510     /* For DTLS if this is the initial handshake, remember the client sequence
1511      * number to use it in our next message (RFC 6347 4.2.1) */
1512 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1513     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM
1514 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1515         && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
1516 #endif
1517         )
1518     {
1519         /* Epoch should be 0 for initial handshakes */
1520         if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 )
1521         {
1522             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1523             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1524         }
1525 
1526         memcpy( ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6 );
1527 
1528 #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
1529         if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 )
1530         {
1531             MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) );
1532             ssl->next_record_offset = 0;
1533             ssl->in_left = 0;
1534             goto read_record_header;
1535         }
1536 
1537         /* No MAC to check yet, so we can update right now */
1538         mbedtls_ssl_dtls_replay_update( ssl );
1539 #endif
1540     }
1541 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1542 
1543     msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1];
1544 
1545 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1546     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
1547     {
1548         /* Set by mbedtls_ssl_read_record() */
1549         msg_len = ssl->in_hslen;
1550     }
1551     else
1552 #endif
1553     {
1554         if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN )
1555         {
1556             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1557             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1558         }
1559 
1560         if( ( ret = mbedtls_ssl_fetch_input( ssl,
1561                        mbedtls_ssl_in_hdr_len( ssl ) + msg_len ) ) != 0 )
1562         {
1563             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret );
1564             return( ret );
1565         }
1566 
1567     /* Done reading this record, get ready for the next one */
1568 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1569         if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1570             ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len( ssl );
1571         else
1572 #endif
1573             ssl->in_left = 0;
1574     }
1575 
1576     buf = ssl->in_msg;
1577 
1578     MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len );
1579 
1580     ssl->handshake->update_checksum( ssl, buf, msg_len );
1581 
1582     /*
1583      * Handshake layer:
1584      *     0  .   0   handshake type
1585      *     1  .   3   handshake length
1586      *     4  .   5   DTLS only: message seqence number
1587      *     6  .   8   DTLS only: fragment offset
1588      *     9  .  11   DTLS only: fragment length
1589      */
1590     if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) )
1591     {
1592         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1593         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1594     }
1595 
1596     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) );
1597 
1598     if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO )
1599     {
1600         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1601         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1602     }
1603 
1604     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d",
1605                    ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) );
1606 
1607     /* We don't support fragmentation of ClientHello (yet?) */
1608     if( buf[1] != 0 ||
1609         msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) )
1610     {
1611         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1612         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1613     }
1614 
1615 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1616     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1617     {
1618         /*
1619          * Copy the client's handshake message_seq on initial handshakes,
1620          * check sequence number on renego.
1621          */
1622 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1623         if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
1624         {
1625             /* This couldn't be done in ssl_prepare_handshake_record() */
1626             unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
1627                                          ssl->in_msg[5];
1628 
1629             if( cli_msg_seq != ssl->handshake->in_msg_seq )
1630             {
1631                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message_seq: "
1632                                     "%u (expected %u)", cli_msg_seq,
1633                                     ssl->handshake->in_msg_seq ) );
1634                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1635             }
1636 
1637             ssl->handshake->in_msg_seq++;
1638         }
1639         else
1640 #endif
1641         {
1642             unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) |
1643                                          ssl->in_msg[5];
1644             ssl->handshake->out_msg_seq = cli_msg_seq;
1645             ssl->handshake->in_msg_seq  = cli_msg_seq + 1;
1646         }
1647 
1648         /*
1649          * For now we don't support fragmentation, so make sure
1650          * fragment_offset == 0 and fragment_length == length
1651          */
1652         if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 ||
1653             memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 )
1654         {
1655             MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) );
1656             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1657         }
1658     }
1659 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1660 
1661     buf += mbedtls_ssl_hs_hdr_len( ssl );
1662     msg_len -= mbedtls_ssl_hs_hdr_len( ssl );
1663 
1664     /*
1665      * ClientHello layer:
1666      *     0  .   1   protocol version
1667      *     2  .  33   random bytes (starting with 4 bytes of Unix time)
1668      *    34  .  35   session id length (1 byte)
1669      *    35  . 34+x  session id
1670      *   35+x . 35+x  DTLS only: cookie length (1 byte)
1671      *   36+x .  ..   DTLS only: cookie
1672      *    ..  .  ..   ciphersuite list length (2 bytes)
1673      *    ..  .  ..   ciphersuite list
1674      *    ..  .  ..   compression alg. list length (1 byte)
1675      *    ..  .  ..   compression alg. list
1676      *    ..  .  ..   extensions length (2 bytes, optional)
1677      *    ..  .  ..   extensions (optional)
1678      */
1679 
1680     /*
1681      * Minimal length (with everything empty and extensions omitted) is
1682      * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can
1683      * read at least up to session id length without worrying.
1684      */
1685     if( msg_len < 38 )
1686     {
1687         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1688         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1689     }
1690 
1691     /*
1692      * Check and save the protocol version
1693      */
1694     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, version", buf, 2 );
1695 
1696     mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
1697                       ssl->conf->transport, buf );
1698 
1699     ssl->handshake->max_major_ver = ssl->major_ver;
1700     ssl->handshake->max_minor_ver = ssl->minor_ver;
1701 
1702     if( ssl->major_ver < ssl->conf->min_major_ver ||
1703         ssl->minor_ver < ssl->conf->min_minor_ver )
1704     {
1705         MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum"
1706                             " [%d:%d] < [%d:%d]",
1707                             ssl->major_ver, ssl->minor_ver,
1708                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) );
1709         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1710                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
1711         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
1712     }
1713 
1714     if( ssl->major_ver > ssl->conf->max_major_ver )
1715     {
1716         ssl->major_ver = ssl->conf->max_major_ver;
1717         ssl->minor_ver = ssl->conf->max_minor_ver;
1718     }
1719     else if( ssl->minor_ver > ssl->conf->max_minor_ver )
1720         ssl->minor_ver = ssl->conf->max_minor_ver;
1721 
1722     /*
1723      * Save client random (inc. Unix time)
1724      */
1725     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf + 2, 32 );
1726 
1727     memcpy( ssl->handshake->randbytes, buf + 2, 32 );
1728 
1729     /*
1730      * Check the session ID length and save session ID
1731      */
1732     sess_len = buf[34];
1733 
1734     if( sess_len > sizeof( ssl->session_negotiate->id ) ||
1735         sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */
1736     {
1737         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1738         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1739                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1740         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1741     }
1742 
1743     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 35, sess_len );
1744 
1745     ssl->session_negotiate->id_len = sess_len;
1746     memset( ssl->session_negotiate->id, 0,
1747             sizeof( ssl->session_negotiate->id ) );
1748     memcpy( ssl->session_negotiate->id, buf + 35,
1749             ssl->session_negotiate->id_len );
1750 
1751     /*
1752      * Check the cookie length and content
1753      */
1754 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1755     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1756     {
1757         cookie_offset = 35 + sess_len;
1758         cookie_len = buf[cookie_offset];
1759 
1760         if( cookie_offset + 1 + cookie_len + 2 > msg_len )
1761         {
1762             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1763             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1764                                             MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
1765             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1766         }
1767 
1768         MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
1769                        buf + cookie_offset + 1, cookie_len );
1770 
1771 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
1772         if( ssl->conf->f_cookie_check != NULL
1773 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1774             && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
1775 #endif
1776             )
1777         {
1778             if( ssl->conf->f_cookie_check( ssl->conf->p_cookie,
1779                                      buf + cookie_offset + 1, cookie_len,
1780                                      ssl->cli_id, ssl->cli_id_len ) != 0 )
1781             {
1782                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) );
1783                 ssl->handshake->verify_cookie_len = 1;
1784             }
1785             else
1786             {
1787                 MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) );
1788                 ssl->handshake->verify_cookie_len = 0;
1789             }
1790         }
1791         else
1792 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
1793         {
1794             /* We know we didn't send a cookie, so it should be empty */
1795             if( cookie_len != 0 )
1796             {
1797                 /* This may be an attacker's probe, so don't send an alert */
1798                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1799                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1800             }
1801 
1802             MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) );
1803         }
1804 
1805     /*
1806      * Check the ciphersuitelist length (will be parsed later)
1807      */
1808         ciph_offset = cookie_offset + 1 + cookie_len;
1809     }
1810     else
1811 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1812         ciph_offset = 35 + sess_len;
1813 
1814     ciph_len = ( buf[ciph_offset + 0] << 8 )
1815              | ( buf[ciph_offset + 1]      );
1816 
1817     if( ciph_len < 2 ||
1818         ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */
1819         ( ciph_len % 2 ) != 0 )
1820     {
1821         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1822         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1823                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1824         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1825     }
1826 
1827     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist",
1828                    buf + ciph_offset + 2,  ciph_len );
1829 
1830     /*
1831      * Check the compression algorithms length and pick one
1832      */
1833     comp_offset = ciph_offset + 2 + ciph_len;
1834 
1835     comp_len = buf[comp_offset];
1836 
1837     if( comp_len < 1 ||
1838         comp_len > 16 ||
1839         comp_len + comp_offset + 1 > msg_len )
1840     {
1841         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1842         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1843                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1844         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1845     }
1846 
1847     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression",
1848                       buf + comp_offset + 1, comp_len );
1849 
1850     ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
1851 #if defined(MBEDTLS_ZLIB_SUPPORT)
1852     for( i = 0; i < comp_len; ++i )
1853     {
1854         if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE )
1855         {
1856             ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE;
1857             break;
1858         }
1859     }
1860 #endif
1861 
1862     /* See comments in ssl_write_client_hello() */
1863 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1864     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1865         ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL;
1866 #endif
1867 
1868     /* Do not parse the extensions if the protocol is SSLv3 */
1869 #if defined(MBEDTLS_SSL_PROTO_SSL3)
1870     if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
1871     {
1872 #endif
1873         /*
1874          * Check the extension length
1875          */
1876         ext_offset = comp_offset + 1 + comp_len;
1877         if( msg_len > ext_offset )
1878         {
1879             if( msg_len < ext_offset + 2 )
1880             {
1881                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1882                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1883                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1884                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1885             }
1886 
1887             ext_len = ( buf[ext_offset + 0] << 8 )
1888                     | ( buf[ext_offset + 1]      );
1889 
1890             if( msg_len != ext_offset + 2 + ext_len )
1891             {
1892                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1893                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1894                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1895                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1896             }
1897         }
1898         else
1899             ext_len = 0;
1900 
1901         ext = buf + ext_offset + 2;
1902         MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len );
1903 
1904         while( ext_len != 0 )
1905         {
1906             unsigned int ext_id;
1907             unsigned int ext_size;
1908             if ( ext_len < 4 ) {
1909                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1910                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1911                                                MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1912                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1913             }
1914             ext_id   = ( ( ext[0] <<  8 ) | ( ext[1] ) );
1915             ext_size = ( ( ext[2] <<  8 ) | ( ext[3] ) );
1916 
1917             if( ext_size + 4 > ext_len )
1918             {
1919                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) );
1920                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1921                                                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1922                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
1923             }
1924             switch( ext_id )
1925             {
1926 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1927             case MBEDTLS_TLS_EXT_SERVERNAME:
1928                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) );
1929                 if( ssl->conf->f_sni == NULL )
1930                     break;
1931 
1932                 ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size );
1933                 if( ret != 0 )
1934                     return( ret );
1935                 break;
1936 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1937 
1938             case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1939                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
1940 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1941                 renegotiation_info_seen = 1;
1942 #endif
1943 
1944                 ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size );
1945                 if( ret != 0 )
1946                     return( ret );
1947                 break;
1948 
1949 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1950     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1951             case MBEDTLS_TLS_EXT_SIG_ALG:
1952                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) );
1953 
1954                 ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size );
1955                 if( ret != 0 )
1956                     return( ret );
1957 
1958                 sig_hash_alg_ext_present = 1;
1959                 break;
1960 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
1961           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1962 
1963 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1964     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1965             case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES:
1966                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported elliptic curves extension" ) );
1967 
1968                 ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size );
1969                 if( ret != 0 )
1970                     return( ret );
1971                 break;
1972 
1973             case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1974                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) );
1975                 ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
1976 
1977                 ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size );
1978                 if( ret != 0 )
1979                     return( ret );
1980                 break;
1981 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
1982           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1983 
1984 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1985             case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1986                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake kkpp extension" ) );
1987 
1988                 ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size );
1989                 if( ret != 0 )
1990                     return( ret );
1991                 break;
1992 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1993 
1994 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1995             case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1996                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) );
1997 
1998                 ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size );
1999                 if( ret != 0 )
2000                     return( ret );
2001                 break;
2002 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
2003 
2004 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
2005             case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
2006                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated hmac extension" ) );
2007 
2008                 ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size );
2009                 if( ret != 0 )
2010                     return( ret );
2011                 break;
2012 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
2013 
2014 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2015             case MBEDTLS_TLS_EXT_CID:
2016                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) );
2017 
2018                 ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size );
2019                 if( ret != 0 )
2020                     return( ret );
2021                 break;
2022 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
2023 
2024 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2025             case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
2026                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt then mac extension" ) );
2027 
2028                 ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size );
2029                 if( ret != 0 )
2030                     return( ret );
2031                 break;
2032 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
2033 
2034 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2035             case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
2036                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended master secret extension" ) );
2037 
2038                 ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size );
2039                 if( ret != 0 )
2040                     return( ret );
2041                 break;
2042 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
2043 
2044 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2045             case MBEDTLS_TLS_EXT_SESSION_TICKET:
2046                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session ticket extension" ) );
2047 
2048                 ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size );
2049                 if( ret != 0 )
2050                     return( ret );
2051                 break;
2052 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2053 
2054 #if defined(MBEDTLS_SSL_ALPN)
2055             case MBEDTLS_TLS_EXT_ALPN:
2056                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
2057 
2058                 ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size );
2059                 if( ret != 0 )
2060                     return( ret );
2061                 break;
2062 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2063 
2064 #if defined(MBEDTLS_SSL_DTLS_SRTP)
2065             case MBEDTLS_TLS_EXT_USE_SRTP:
2066                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "found use_srtp extension" ) );
2067 
2068                 ret = ssl_parse_use_srtp_ext( ssl, ext + 4, ext_size );
2069                 if( ret != 0 )
2070                     return( ret );
2071                 break;
2072 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2073 
2074             default:
2075                 MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %u (ignoring)",
2076                                ext_id ) );
2077             }
2078 
2079             ext_len -= 4 + ext_size;
2080             ext += 4 + ext_size;
2081         }
2082 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2083     }
2084 #endif
2085 
2086 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
2087     for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
2088     {
2089         if( MBEDTLS_GET_UINT16_BE( p, 0 ) == MBEDTLS_SSL_FALLBACK_SCSV_VALUE )
2090         {
2091             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received FALLBACK_SCSV" ) );
2092 
2093             if( ssl->minor_ver < ssl->conf->max_minor_ver )
2094             {
2095                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) );
2096 
2097                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2098                                         MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK );
2099 
2100                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
2101             }
2102 
2103             break;
2104         }
2105     }
2106 #endif /* MBEDTLS_SSL_FALLBACK_SCSV */
2107 
2108 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
2109     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
2110 
2111     /*
2112      * Try to fall back to default hash SHA1 if the client
2113      * hasn't provided any preferred signature-hash combinations.
2114      */
2115     if( sig_hash_alg_ext_present == 0 )
2116     {
2117         mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1;
2118 
2119         if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 )
2120             md_default = MBEDTLS_MD_NONE;
2121 
2122         mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default );
2123     }
2124 
2125 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
2126           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2127 
2128     /*
2129      * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
2130      */
2131     for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 )
2132     {
2133         if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO )
2134         {
2135             MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) );
2136 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2137             if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
2138             {
2139                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV "
2140                                             "during renegotiation" ) );
2141                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2142                                                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2143                 return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
2144             }
2145 #endif
2146             ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
2147             break;
2148         }
2149     }
2150 
2151     /*
2152      * Renegotiation security checks
2153      */
2154     if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
2155         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
2156     {
2157         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
2158         handshake_failure = 1;
2159     }
2160 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2161     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2162              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
2163              renegotiation_info_seen == 0 )
2164     {
2165         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
2166         handshake_failure = 1;
2167     }
2168     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2169              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
2170              ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
2171     {
2172         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
2173         handshake_failure = 1;
2174     }
2175     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2176              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
2177              renegotiation_info_seen == 1 )
2178     {
2179         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
2180         handshake_failure = 1;
2181     }
2182 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2183 
2184     if( handshake_failure == 1 )
2185     {
2186         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2187                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2188         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO );
2189     }
2190 
2191     /*
2192      * Search for a matching ciphersuite
2193      * (At the end because we need information from the EC-based extensions
2194      * and certificate from the SNI callback triggered by the SNI extension.)
2195      */
2196     got_common_suite = 0;
2197     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
2198     ciphersuite_info = NULL;
2199 #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE)
2200     for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
2201         for( i = 0; ciphersuites[i] != 0; i++ )
2202 #else
2203     for( i = 0; ciphersuites[i] != 0; i++ )
2204         for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 )
2205 #endif
2206         {
2207             if( MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i] )
2208                 continue;
2209 
2210             got_common_suite = 1;
2211 
2212             if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i],
2213                                                &ciphersuite_info ) ) != 0 )
2214                 return( ret );
2215 
2216             if( ciphersuite_info != NULL )
2217                 goto have_ciphersuite;
2218         }
2219 
2220     if( got_common_suite )
2221     {
2222         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, "
2223                             "but none of them usable" ) );
2224         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2225                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2226         return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE );
2227     }
2228     else
2229     {
2230         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) );
2231         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2232                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2233         return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
2234     }
2235 
2236 have_ciphersuite:
2237     MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) );
2238 
2239     ssl->session_negotiate->ciphersuite = ciphersuites[i];
2240     ssl->handshake->ciphersuite_info = ciphersuite_info;
2241 
2242     ssl->state++;
2243 
2244 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2245     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2246         mbedtls_ssl_recv_flight_completed( ssl );
2247 #endif
2248 
2249     /* Debugging-only output for testsuite */
2250 #if defined(MBEDTLS_DEBUG_C)                         && \
2251     defined(MBEDTLS_SSL_PROTO_TLS1_2)                && \
2252     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
2253     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
2254     {
2255         mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info );
2256         if( sig_alg != MBEDTLS_PK_NONE )
2257         {
2258             mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
2259                                                                   sig_alg );
2260             MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d",
2261                                         mbedtls_ssl_hash_from_md_alg( md_alg ) ) );
2262         }
2263         else
2264         {
2265             MBEDTLS_SSL_DEBUG_MSG( 3, ( "no hash algorithm for signature algorithm "
2266                                         "%u - should not happen", (unsigned) sig_alg ) );
2267         }
2268     }
2269 #endif
2270 
2271     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) );
2272 
2273     return( 0 );
2274 }
2275 
2276 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2277 static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
2278                                           unsigned char *buf,
2279                                           size_t *olen )
2280 {
2281     unsigned char *p = buf;
2282 
2283     if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
2284     {
2285         *olen = 0;
2286         return;
2287     }
2288 
2289     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding truncated hmac extension" ) );
2290 
2291     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_TRUNCATED_HMAC, p, 0 );
2292     p += 2;
2293 
2294     *p++ = 0x00;
2295     *p++ = 0x00;
2296 
2297     *olen = 4;
2298 }
2299 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
2300 
2301 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
ssl_write_cid_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2302 static void ssl_write_cid_ext( mbedtls_ssl_context *ssl,
2303                                unsigned char *buf,
2304                                size_t *olen )
2305 {
2306     unsigned char *p = buf;
2307     size_t ext_len;
2308     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2309 
2310     *olen = 0;
2311 
2312     /* Skip writing the extension if we don't want to use it or if
2313      * the client hasn't offered it. */
2314     if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED )
2315         return;
2316 
2317     /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX
2318      * which is at most 255, so the increment cannot overflow. */
2319     if( end < p || (size_t)( end - p ) < (unsigned)( ssl->own_cid_len + 5 ) )
2320     {
2321         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
2322         return;
2323     }
2324 
2325     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding CID extension" ) );
2326 
2327     /*
2328      * Quoting draft-ietf-tls-dtls-connection-id-05
2329      * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
2330      *
2331      *   struct {
2332      *      opaque cid<0..2^8-1>;
2333      *   } ConnectionId;
2334     */
2335     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_CID, p, 0 );
2336     p += 2;
2337     ext_len = (size_t) ssl->own_cid_len + 1;
2338     MBEDTLS_PUT_UINT16_BE( ext_len, p, 0 );
2339     p += 2;
2340 
2341     *p++ = (uint8_t) ssl->own_cid_len;
2342     memcpy( p, ssl->own_cid, ssl->own_cid_len );
2343 
2344     *olen = ssl->own_cid_len + 5;
2345 }
2346 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2347 
2348 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2349 static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
2350                                             unsigned char *buf,
2351                                             size_t *olen )
2352 {
2353     unsigned char *p = buf;
2354     const mbedtls_ssl_ciphersuite_t *suite = NULL;
2355     const mbedtls_cipher_info_t *cipher = NULL;
2356 
2357     if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
2358         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
2359     {
2360         *olen = 0;
2361         return;
2362     }
2363 
2364     /*
2365      * RFC 7366: "If a server receives an encrypt-then-MAC request extension
2366      * from a client and then selects a stream or Authenticated Encryption
2367      * with Associated Data (AEAD) ciphersuite, it MUST NOT send an
2368      * encrypt-then-MAC response extension back to the client."
2369      */
2370     if( ( suite = mbedtls_ssl_ciphersuite_from_id(
2371                     ssl->session_negotiate->ciphersuite ) ) == NULL ||
2372         ( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL ||
2373         cipher->mode != MBEDTLS_MODE_CBC )
2374     {
2375         *olen = 0;
2376         return;
2377     }
2378 
2379     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding encrypt then mac extension" ) );
2380 
2381     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC, p, 0 );
2382     p += 2;
2383 
2384     *p++ = 0x00;
2385     *p++ = 0x00;
2386 
2387     *olen = 4;
2388 }
2389 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
2390 
2391 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2392 static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
2393                                        unsigned char *buf,
2394                                        size_t *olen )
2395 {
2396     unsigned char *p = buf;
2397 
2398     if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
2399         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
2400     {
2401         *olen = 0;
2402         return;
2403     }
2404 
2405     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding extended master secret "
2406                         "extension" ) );
2407 
2408     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET, p, 0 );
2409     p += 2;
2410 
2411     *p++ = 0x00;
2412     *p++ = 0x00;
2413 
2414     *olen = 4;
2415 }
2416 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
2417 
2418 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2419 static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
2420                                           unsigned char *buf,
2421                                           size_t *olen )
2422 {
2423     unsigned char *p = buf;
2424 
2425     if( ssl->handshake->new_session_ticket == 0 )
2426     {
2427         *olen = 0;
2428         return;
2429     }
2430 
2431     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding session ticket extension" ) );
2432 
2433     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_SESSION_TICKET, p, 0 );
2434     p += 2;
2435 
2436     *p++ = 0x00;
2437     *p++ = 0x00;
2438 
2439     *olen = 4;
2440 }
2441 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2442 
ssl_write_renegotiation_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2443 static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
2444                                          unsigned char *buf,
2445                                          size_t *olen )
2446 {
2447     unsigned char *p = buf;
2448 
2449     if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION )
2450     {
2451         *olen = 0;
2452         return;
2453     }
2454 
2455     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, secure renegotiation extension" ) );
2456 
2457     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO, p, 0 );
2458     p += 2;
2459 
2460 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2461     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
2462     {
2463         *p++ = 0x00;
2464         *p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF;
2465         *p++ = ssl->verify_data_len * 2 & 0xFF;
2466 
2467         memcpy( p, ssl->peer_verify_data, ssl->verify_data_len );
2468         p += ssl->verify_data_len;
2469         memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
2470         p += ssl->verify_data_len;
2471     }
2472     else
2473 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2474     {
2475         *p++ = 0x00;
2476         *p++ = 0x01;
2477         *p++ = 0x00;
2478     }
2479 
2480     *olen = p - buf;
2481 }
2482 
2483 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2484 static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
2485                                                unsigned char *buf,
2486                                                size_t *olen )
2487 {
2488     unsigned char *p = buf;
2489 
2490     if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE )
2491     {
2492         *olen = 0;
2493         return;
2494     }
2495 
2496     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) );
2497 
2498     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH, p, 0 );
2499     p += 2;
2500 
2501     *p++ = 0x00;
2502     *p++ = 1;
2503 
2504     *p++ = ssl->session_negotiate->mfl_code;
2505 
2506     *olen = 5;
2507 }
2508 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
2509 
2510 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
2511     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_point_formats_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2512 static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
2513                                                    unsigned char *buf,
2514                                                    size_t *olen )
2515 {
2516     unsigned char *p = buf;
2517     ((void) ssl);
2518 
2519     if( ( ssl->handshake->cli_exts &
2520           MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 )
2521     {
2522         *olen = 0;
2523         return;
2524     }
2525 
2526     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) );
2527 
2528     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS, p, 0 );
2529     p += 2;
2530 
2531     *p++ = 0x00;
2532     *p++ = 2;
2533 
2534     *p++ = 1;
2535     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
2536 
2537     *olen = 6;
2538 }
2539 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2540 
2541 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2542 static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
2543                                         unsigned char *buf,
2544                                         size_t *olen )
2545 {
2546     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2547     unsigned char *p = buf;
2548     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2549     size_t kkpp_len;
2550 
2551     *olen = 0;
2552 
2553     /* Skip costly computation if not needed */
2554     if( ssl->handshake->ciphersuite_info->key_exchange !=
2555         MBEDTLS_KEY_EXCHANGE_ECJPAKE )
2556         return;
2557 
2558     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, ecjpake kkpp extension" ) );
2559 
2560     if( end - p < 4 )
2561     {
2562         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
2563         return;
2564     }
2565 
2566     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0 );
2567     p += 2;
2568 
2569     ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
2570                                         p + 2, end - p - 2, &kkpp_len,
2571                                         ssl->conf->f_rng, ssl->conf->p_rng );
2572     if( ret != 0 )
2573     {
2574         MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
2575         return;
2576     }
2577 
2578     MBEDTLS_PUT_UINT16_BE( kkpp_len, p, 0 );
2579     p += 2;
2580 
2581     *olen = kkpp_len + 4;
2582 }
2583 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2584 
2585 #if defined(MBEDTLS_SSL_ALPN )
ssl_write_alpn_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2586 static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
2587                                 unsigned char *buf, size_t *olen )
2588 {
2589     if( ssl->alpn_chosen == NULL )
2590     {
2591         *olen = 0;
2592         return;
2593     }
2594 
2595     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) );
2596 
2597     /*
2598      * 0 . 1    ext identifier
2599      * 2 . 3    ext length
2600      * 4 . 5    protocol list length
2601      * 6 . 6    protocol name length
2602      * 7 . 7+n  protocol name
2603      */
2604     MBEDTLS_PUT_UINT16_BE( MBEDTLS_TLS_EXT_ALPN, buf, 0);
2605 
2606     *olen = 7 + strlen( ssl->alpn_chosen );
2607 
2608     MBEDTLS_PUT_UINT16_BE( *olen - 4, buf, 2 );
2609 
2610     MBEDTLS_PUT_UINT16_BE( *olen - 6, buf, 4 );
2611 
2612     buf[6] = MBEDTLS_BYTE_0( *olen - 7 );
2613 
2614     memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 );
2615 }
2616 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */
2617 
2618 #if defined(MBEDTLS_SSL_DTLS_SRTP ) && defined(MBEDTLS_SSL_PROTO_DTLS)
ssl_write_use_srtp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,size_t * olen)2619 static void ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl,
2620                                     unsigned char *buf,
2621                                     size_t *olen )
2622 {
2623     size_t mki_len = 0, ext_len = 0;
2624     uint16_t profile_value = 0;
2625     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2626 
2627     *olen = 0;
2628 
2629     if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
2630         ( ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET ) )
2631     {
2632         return;
2633     }
2634 
2635     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding use_srtp extension" ) );
2636 
2637     if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED )
2638     {
2639         mki_len = ssl->dtls_srtp_info.mki_len;
2640     }
2641 
2642     /* The extension total size is 9 bytes :
2643      * - 2 bytes for the extension tag
2644      * - 2 bytes for the total size
2645      * - 2 bytes for the protection profile length
2646      * - 2 bytes for the protection profile
2647      * - 1 byte for the mki length
2648      * +  the actual mki length
2649      * Check we have enough room in the output buffer */
2650     if( (size_t)( end - buf ) < mki_len + 9 )
2651     {
2652         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
2653         return;
2654     }
2655 
2656     /* extension */
2657     MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_USE_SRTP, buf, 0 );
2658     /*
2659      * total length 5 and mki value: only one profile(2 bytes)
2660      *              and length(2 bytes) and srtp_mki  )
2661      */
2662     ext_len = 5 + mki_len;
2663     MBEDTLS_PUT_UINT16_BE( ext_len, buf, 2 );
2664 
2665     /* protection profile length: 2 */
2666     buf[4] = 0x00;
2667     buf[5] = 0x02;
2668     profile_value = mbedtls_ssl_check_srtp_profile_value(
2669                                 ssl->dtls_srtp_info.chosen_dtls_srtp_profile );
2670     if( profile_value != MBEDTLS_TLS_SRTP_UNSET )
2671     {
2672         MBEDTLS_PUT_UINT16_BE( profile_value, buf, 6 );
2673     }
2674     else
2675     {
2676         MBEDTLS_SSL_DEBUG_MSG( 1, ( "use_srtp extension invalid profile" ) );
2677         return;
2678     }
2679 
2680     buf[8] = mki_len & 0xFF;
2681     memcpy( &buf[9], ssl->dtls_srtp_info.mki_value, mki_len );
2682 
2683     *olen = 9 + mki_len;
2684 }
2685 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2686 
2687 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
ssl_write_hello_verify_request(mbedtls_ssl_context * ssl)2688 static int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl )
2689 {
2690     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2691     unsigned char *p = ssl->out_msg + 4;
2692     unsigned char *cookie_len_byte;
2693 
2694     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello verify request" ) );
2695 
2696     /*
2697      * struct {
2698      *   ProtocolVersion server_version;
2699      *   opaque cookie<0..2^8-1>;
2700      * } HelloVerifyRequest;
2701      */
2702 
2703     /* The RFC is not clear on this point, but sending the actual negotiated
2704      * version looks like the most interoperable thing to do. */
2705     mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2706                        ssl->conf->transport, p );
2707     MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
2708     p += 2;
2709 
2710     /* If we get here, f_cookie_check is not null */
2711     if( ssl->conf->f_cookie_write == NULL )
2712     {
2713         MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) );
2714         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2715     }
2716 
2717     /* Skip length byte until we know the length */
2718     cookie_len_byte = p++;
2719 
2720     if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie,
2721                                      &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,
2722                                      ssl->cli_id, ssl->cli_id_len ) ) != 0 )
2723     {
2724         MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret );
2725         return( ret );
2726     }
2727 
2728     *cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) );
2729 
2730     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte );
2731 
2732     ssl->out_msglen  = p - ssl->out_msg;
2733     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2734     ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
2735 
2736     ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
2737 
2738     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
2739     {
2740         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
2741         return( ret );
2742     }
2743 
2744 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2745     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2746         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
2747     {
2748         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
2749         return( ret );
2750     }
2751 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2752 
2753     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello verify request" ) );
2754 
2755     return( 0 );
2756 }
2757 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2758 
ssl_handle_id_based_session_resumption(mbedtls_ssl_context * ssl)2759 static void ssl_handle_id_based_session_resumption( mbedtls_ssl_context *ssl )
2760 {
2761     int ret;
2762     mbedtls_ssl_session session_tmp;
2763     mbedtls_ssl_session * const session = ssl->session_negotiate;
2764 
2765     /* Resume is 0  by default, see ssl_handshake_init().
2766      * It may be already set to 1 by ssl_parse_session_ticket_ext(). */
2767     if( ssl->handshake->resume == 1 )
2768         return;
2769     if( session->id_len == 0 )
2770         return;
2771     if( ssl->conf->f_get_cache == NULL )
2772         return;
2773 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2774     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
2775         return;
2776 #endif
2777 
2778     mbedtls_ssl_session_init( &session_tmp );
2779 
2780     session_tmp.id_len = session->id_len;
2781     memcpy( session_tmp.id, session->id, session->id_len );
2782 
2783     ret = ssl->conf->f_get_cache( ssl->conf->p_cache,
2784                                   &session_tmp );
2785     if( ret != 0 )
2786         goto exit;
2787 
2788     if( session->ciphersuite != session_tmp.ciphersuite ||
2789         session->compression != session_tmp.compression )
2790     {
2791         /* Mismatch between cached and negotiated session */
2792         goto exit;
2793     }
2794 
2795     /* Move semantics */
2796     mbedtls_ssl_session_free( session );
2797     *session = session_tmp;
2798     memset( &session_tmp, 0, sizeof( session_tmp ) );
2799 
2800     MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from cache" ) );
2801     ssl->handshake->resume = 1;
2802 
2803 exit:
2804 
2805     mbedtls_ssl_session_free( &session_tmp );
2806 }
2807 
ssl_write_server_hello(mbedtls_ssl_context * ssl)2808 static int ssl_write_server_hello( mbedtls_ssl_context *ssl )
2809 {
2810 #if defined(MBEDTLS_HAVE_TIME)
2811     mbedtls_time_t t;
2812 #endif
2813     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2814     size_t olen, ext_len = 0, n;
2815     unsigned char *buf, *p;
2816 
2817     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) );
2818 
2819 #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2820     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2821         ssl->handshake->verify_cookie_len != 0 )
2822     {
2823         MBEDTLS_SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) );
2824         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
2825 
2826         return( ssl_write_hello_verify_request( ssl ) );
2827     }
2828 #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2829 
2830     if( ssl->conf->f_rng == NULL )
2831     {
2832         MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
2833         return( MBEDTLS_ERR_SSL_NO_RNG );
2834     }
2835 
2836     /*
2837      *     0  .   0   handshake type
2838      *     1  .   3   handshake length
2839      *     4  .   5   protocol version
2840      *     6  .   9   UNIX time()
2841      *    10  .  37   random bytes
2842      */
2843     buf = ssl->out_msg;
2844     p = buf + 4;
2845 
2846     mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver,
2847                        ssl->conf->transport, p );
2848     p += 2;
2849 
2850     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [%d:%d]",
2851                         buf[4], buf[5] ) );
2852 
2853 #if defined(MBEDTLS_HAVE_TIME)
2854     t = mbedtls_time( NULL );
2855     MBEDTLS_PUT_UINT32_BE( t, p, 0 );
2856     p += 4;
2857 
2858     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %" MBEDTLS_PRINTF_LONGLONG,
2859                                 (long long) t ) );
2860 #else
2861     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
2862         return( ret );
2863 
2864     p += 4;
2865 #endif /* MBEDTLS_HAVE_TIME */
2866 
2867     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
2868         return( ret );
2869 
2870     p += 28;
2871 
2872     memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 );
2873 
2874     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 6, 32 );
2875 
2876     ssl_handle_id_based_session_resumption( ssl );
2877 
2878     if( ssl->handshake->resume == 0 )
2879     {
2880         /*
2881          * New session, create a new session id,
2882          * unless we're about to issue a session ticket
2883          */
2884         ssl->state++;
2885 
2886 #if defined(MBEDTLS_HAVE_TIME)
2887         ssl->session_negotiate->start = mbedtls_time( NULL );
2888 #endif
2889 
2890 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2891         if( ssl->handshake->new_session_ticket != 0 )
2892         {
2893             ssl->session_negotiate->id_len = n = 0;
2894             memset( ssl->session_negotiate->id, 0, 32 );
2895         }
2896         else
2897 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2898         {
2899             ssl->session_negotiate->id_len = n = 32;
2900             if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id,
2901                                     n ) ) != 0 )
2902                 return( ret );
2903         }
2904     }
2905     else
2906     {
2907         /*
2908          * Resuming a session
2909          */
2910         n = ssl->session_negotiate->id_len;
2911         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
2912 
2913         if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
2914         {
2915             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
2916             return( ret );
2917         }
2918     }
2919 
2920     /*
2921      *    38  .  38     session id length
2922      *    39  . 38+n    session id
2923      *   39+n . 40+n    chosen ciphersuite
2924      *   41+n . 41+n    chosen compression alg.
2925      *   42+n . 43+n    extensions length
2926      *   44+n . 43+n+m  extensions
2927      */
2928     *p++ = (unsigned char) ssl->session_negotiate->id_len;
2929     memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len );
2930     p += ssl->session_negotiate->id_len;
2931 
2932     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n ) );
2933     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, session id", buf + 39, n );
2934     MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
2935                    ssl->handshake->resume ? "a" : "no" ) );
2936 
2937     MBEDTLS_PUT_UINT16_BE( ssl->session_negotiate->ciphersuite, p, 0 );
2938     p += 2;
2939     *p++ = MBEDTLS_BYTE_0( ssl->session_negotiate->compression );
2940 
2941     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s",
2942            mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) );
2943     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: 0x%02X",
2944                    (unsigned int) ssl->session_negotiate->compression ) );
2945 
2946     /* Do not write the extensions if the protocol is SSLv3 */
2947 #if defined(MBEDTLS_SSL_PROTO_SSL3)
2948     if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) )
2949     {
2950 #endif
2951 
2952     /*
2953      *  First write extensions, then the total length
2954      */
2955     ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
2956     ext_len += olen;
2957 
2958 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2959     ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
2960     ext_len += olen;
2961 #endif
2962 
2963 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
2964     ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
2965     ext_len += olen;
2966 #endif
2967 
2968 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2969     ssl_write_cid_ext( ssl, p + 2 + ext_len, &olen );
2970     ext_len += olen;
2971 #endif
2972 
2973 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2974     ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
2975     ext_len += olen;
2976 #endif
2977 
2978 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2979     ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
2980     ext_len += olen;
2981 #endif
2982 
2983 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2984     ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
2985     ext_len += olen;
2986 #endif
2987 
2988 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
2989     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2990     if ( mbedtls_ssl_ciphersuite_uses_ec(
2991          mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) )
2992     {
2993         ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
2994         ext_len += olen;
2995     }
2996 #endif
2997 
2998 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2999     ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
3000     ext_len += olen;
3001 #endif
3002 
3003 #if defined(MBEDTLS_SSL_ALPN)
3004     ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
3005     ext_len += olen;
3006 #endif
3007 
3008 #if defined(MBEDTLS_SSL_DTLS_SRTP)
3009     ssl_write_use_srtp_ext( ssl, p + 2 + ext_len, &olen );
3010     ext_len += olen;
3011 #endif
3012 
3013     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, total extension length: %" MBEDTLS_PRINTF_SIZET,
3014                                 ext_len ) );
3015 
3016     if( ext_len > 0 )
3017     {
3018         MBEDTLS_PUT_UINT16_BE( ext_len, p, 0 );
3019         p += 2 + ext_len;
3020     }
3021 
3022 #if defined(MBEDTLS_SSL_PROTO_SSL3)
3023     }
3024 #endif
3025 
3026     ssl->out_msglen  = p - buf;
3027     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3028     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;
3029 
3030     ret = mbedtls_ssl_write_handshake_msg( ssl );
3031 
3032     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) );
3033 
3034     return( ret );
3035 }
3036 
3037 #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
ssl_write_certificate_request(mbedtls_ssl_context * ssl)3038 static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
3039 {
3040     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3041         ssl->handshake->ciphersuite_info;
3042 
3043     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
3044 
3045     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
3046     {
3047         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
3048         ssl->state++;
3049         return( 0 );
3050     }
3051 
3052     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3053     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3054 }
3055 #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
ssl_write_certificate_request(mbedtls_ssl_context * ssl)3056 static int ssl_write_certificate_request( mbedtls_ssl_context *ssl )
3057 {
3058     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3059     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3060         ssl->handshake->ciphersuite_info;
3061     uint16_t dn_size, total_dn_size; /* excluding length bytes */
3062     size_t ct_len, sa_len; /* including length bytes */
3063     unsigned char *buf, *p;
3064     const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
3065     const mbedtls_x509_crt *crt;
3066     int authmode;
3067 
3068     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) );
3069 
3070     ssl->state++;
3071 
3072 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
3073     if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET )
3074         authmode = ssl->handshake->sni_authmode;
3075     else
3076 #endif
3077         authmode = ssl->conf->authmode;
3078 
3079     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ||
3080         authmode == MBEDTLS_SSL_VERIFY_NONE )
3081     {
3082         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) );
3083         return( 0 );
3084     }
3085 
3086     /*
3087      *     0  .   0   handshake type
3088      *     1  .   3   handshake length
3089      *     4  .   4   cert type count
3090      *     5  .. m-1  cert types
3091      *     m  .. m+1  sig alg length (TLS 1.2 only)
3092      *    m+1 .. n-1  SignatureAndHashAlgorithms (TLS 1.2 only)
3093      *     n  .. n+1  length of all DNs
3094      *    n+2 .. n+3  length of DN 1
3095      *    n+4 .. ...  Distinguished Name #1
3096      *    ... .. ...  length of DN 2, etc.
3097      */
3098     buf = ssl->out_msg;
3099     p = buf + 4;
3100 
3101     /*
3102      * Supported certificate types
3103      *
3104      *     ClientCertificateType certificate_types<1..2^8-1>;
3105      *     enum { (255) } ClientCertificateType;
3106      */
3107     ct_len = 0;
3108 
3109 #if defined(MBEDTLS_RSA_C)
3110     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
3111 #endif
3112 #if defined(MBEDTLS_ECDSA_C)
3113     p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;
3114 #endif
3115 
3116     p[0] = (unsigned char) ct_len++;
3117     p += ct_len;
3118 
3119     sa_len = 0;
3120 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3121     /*
3122      * Add signature_algorithms for verify (TLS 1.2)
3123      *
3124      *     SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;
3125      *
3126      *     struct {
3127      *           HashAlgorithm hash;
3128      *           SignatureAlgorithm signature;
3129      *     } SignatureAndHashAlgorithm;
3130      *
3131      *     enum { (255) } HashAlgorithm;
3132      *     enum { (255) } SignatureAlgorithm;
3133      */
3134     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
3135     {
3136         const int *cur;
3137 
3138         /*
3139          * Supported signature algorithms
3140          */
3141         for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ )
3142         {
3143             unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur );
3144 
3145             if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) )
3146                 continue;
3147 
3148 #if defined(MBEDTLS_RSA_C)
3149             p[2 + sa_len++] = hash;
3150             p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA;
3151 #endif
3152 #if defined(MBEDTLS_ECDSA_C)
3153             p[2 + sa_len++] = hash;
3154             p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA;
3155 #endif
3156         }
3157 
3158         MBEDTLS_PUT_UINT16_BE( sa_len, p, 0 );
3159         sa_len += 2;
3160         p += sa_len;
3161     }
3162 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3163 
3164     /*
3165      * DistinguishedName certificate_authorities<0..2^16-1>;
3166      * opaque DistinguishedName<1..2^16-1>;
3167      */
3168     p += 2;
3169 
3170     total_dn_size = 0;
3171 
3172     if( ssl->conf->cert_req_ca_list ==  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED )
3173     {
3174         /* NOTE: If trusted certificates are provisioned
3175          *       via a CA callback (configured through
3176          *       `mbedtls_ssl_conf_ca_cb()`, then the
3177          *       CertificateRequest is currently left empty. */
3178 
3179 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
3180         if( ssl->handshake->sni_ca_chain != NULL )
3181             crt = ssl->handshake->sni_ca_chain;
3182         else
3183 #endif
3184             crt = ssl->conf->ca_chain;
3185 
3186         while( crt != NULL && crt->version != 0 )
3187         {
3188             /* It follows from RFC 5280 A.1 that this length
3189              * can be represented in at most 11 bits. */
3190             dn_size = (uint16_t) crt->subject_raw.len;
3191 
3192             if( end < p || (size_t)( end - p ) < 2 + (size_t) dn_size )
3193             {
3194                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) );
3195                 break;
3196             }
3197 
3198             MBEDTLS_PUT_UINT16_BE( dn_size, p, 0 );
3199             p += 2;
3200             memcpy( p, crt->subject_raw.p, dn_size );
3201             p += dn_size;
3202 
3203             MBEDTLS_SSL_DEBUG_BUF( 3, "requested DN", p - dn_size, dn_size );
3204 
3205             total_dn_size += 2 + dn_size;
3206             crt = crt->next;
3207         }
3208     }
3209 
3210     ssl->out_msglen  = p - buf;
3211     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3212     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;
3213     MBEDTLS_PUT_UINT16_BE( total_dn_size, ssl->out_msg, 4 + ct_len + sa_len );
3214 
3215     ret = mbedtls_ssl_write_handshake_msg( ssl );
3216 
3217     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) );
3218 
3219     return( ret );
3220 }
3221 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
3222 
3223 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
3224     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
ssl_get_ecdh_params_from_cert(mbedtls_ssl_context * ssl)3225 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
3226 {
3227     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3228 
3229     if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) )
3230     {
3231         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
3232         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
3233     }
3234 
3235     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx,
3236                                  mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ),
3237                                  MBEDTLS_ECDH_OURS ) ) != 0 )
3238     {
3239         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
3240         return( ret );
3241     }
3242 
3243     return( 0 );
3244 }
3245 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
3246           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3247 
3248 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
3249     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
ssl_resume_server_key_exchange(mbedtls_ssl_context * ssl,size_t * signature_len)3250 static int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl,
3251                                            size_t *signature_len )
3252 {
3253     /* Append the signature to ssl->out_msg, leaving 2 bytes for the
3254      * signature length which will be added in ssl_write_server_key_exchange
3255      * after the call to ssl_prepare_server_key_exchange.
3256      * ssl_write_server_key_exchange also takes care of incrementing
3257      * ssl->out_msglen. */
3258     unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;
3259     size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN
3260                            - sig_start );
3261     int ret = ssl->conf->f_async_resume( ssl,
3262                                          sig_start, signature_len, sig_max_len );
3263     if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
3264     {
3265         ssl->handshake->async_in_progress = 0;
3266         mbedtls_ssl_set_async_operation_data( ssl, NULL );
3267     }
3268     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_resume_server_key_exchange", ret );
3269     return( ret );
3270 }
3271 #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
3272           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
3273 
3274 /* Prepare the ServerKeyExchange message, up to and including
3275  * calculating the signature if any, but excluding formatting the
3276  * signature and sending the message. */
ssl_prepare_server_key_exchange(mbedtls_ssl_context * ssl,size_t * signature_len)3277 static int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl,
3278                                             size_t *signature_len )
3279 {
3280     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3281         ssl->handshake->ciphersuite_info;
3282 
3283 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED)
3284 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3285     unsigned char *dig_signed = NULL;
3286 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3287 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */
3288 
3289     (void) ciphersuite_info; /* unused in some configurations */
3290 #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3291     (void) signature_len;
3292 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3293 
3294     ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */
3295 
3296     /*
3297      *
3298      * Part 1: Provide key exchange parameters for chosen ciphersuite.
3299      *
3300      */
3301 
3302     /*
3303      * - ECJPAKE key exchanges
3304      */
3305 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3306     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
3307     {
3308         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3309         size_t len = 0;
3310 
3311         ret = mbedtls_ecjpake_write_round_two(
3312             &ssl->handshake->ecjpake_ctx,
3313             ssl->out_msg + ssl->out_msglen,
3314             MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
3315             ssl->conf->f_rng, ssl->conf->p_rng );
3316         if( ret != 0 )
3317         {
3318             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
3319             return( ret );
3320         }
3321 
3322         ssl->out_msglen += len;
3323     }
3324 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
3325 
3326     /*
3327      * For (EC)DHE key exchanges with PSK, parameters are prefixed by support
3328      * identity hint (RFC 4279, Sec. 3). Until someone needs this feature,
3329      * we use empty support identity hints here.
3330      **/
3331 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)   || \
3332     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3333     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
3334         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
3335     {
3336         ssl->out_msg[ssl->out_msglen++] = 0x00;
3337         ssl->out_msg[ssl->out_msglen++] = 0x00;
3338     }
3339 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||
3340           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
3341 
3342     /*
3343      * - DHE key exchanges
3344      */
3345 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED)
3346     if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) )
3347     {
3348         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3349         size_t len = 0;
3350 
3351         if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL )
3352         {
3353             MBEDTLS_SSL_DEBUG_MSG( 1, ( "no DH parameters set" ) );
3354             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3355         }
3356 
3357         /*
3358          * Ephemeral DH parameters:
3359          *
3360          * struct {
3361          *     opaque dh_p<1..2^16-1>;
3362          *     opaque dh_g<1..2^16-1>;
3363          *     opaque dh_Ys<1..2^16-1>;
3364          * } ServerDHParams;
3365          */
3366         if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx,
3367                                            &ssl->conf->dhm_P,
3368                                            &ssl->conf->dhm_G ) ) != 0 )
3369         {
3370             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_set_group", ret );
3371             return( ret );
3372         }
3373 
3374         if( ( ret = mbedtls_dhm_make_params(
3375                   &ssl->handshake->dhm_ctx,
3376                   (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
3377                   ssl->out_msg + ssl->out_msglen, &len,
3378                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3379         {
3380             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_params", ret );
3381             return( ret );
3382         }
3383 
3384 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3385         dig_signed = ssl->out_msg + ssl->out_msglen;
3386 #endif
3387 
3388         ssl->out_msglen += len;
3389 
3390         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
3391         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P  );
3392         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G  );
3393         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
3394     }
3395 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */
3396 
3397     /*
3398      * - ECDHE key exchanges
3399      */
3400 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
3401     if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) )
3402     {
3403         /*
3404          * Ephemeral ECDH parameters:
3405          *
3406          * struct {
3407          *     ECParameters curve_params;
3408          *     ECPoint      public;
3409          * } ServerECDHParams;
3410          */
3411         const mbedtls_ecp_curve_info **curve = NULL;
3412         const mbedtls_ecp_group_id *gid;
3413         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3414         size_t len = 0;
3415 
3416         /* Match our preference list against the offered curves */
3417         for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ )
3418             for( curve = ssl->handshake->curves; *curve != NULL; curve++ )
3419                 if( (*curve)->grp_id == *gid )
3420                     goto curve_matching_done;
3421 
3422 curve_matching_done:
3423         if( curve == NULL || *curve == NULL )
3424         {
3425             MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) );
3426             return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN );
3427         }
3428 
3429         MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", (*curve)->name ) );
3430 
3431         if( ( ret = mbedtls_ecdh_setup( &ssl->handshake->ecdh_ctx,
3432                                         (*curve)->grp_id ) ) != 0 )
3433         {
3434             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret );
3435             return( ret );
3436         }
3437 
3438         if( ( ret = mbedtls_ecdh_make_params(
3439                   &ssl->handshake->ecdh_ctx, &len,
3440                   ssl->out_msg + ssl->out_msglen,
3441                   MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
3442                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3443         {
3444             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret );
3445             return( ret );
3446         }
3447 
3448 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3449         dig_signed = ssl->out_msg + ssl->out_msglen;
3450 #endif
3451 
3452         ssl->out_msglen += len;
3453 
3454         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
3455                                 MBEDTLS_DEBUG_ECDH_Q );
3456     }
3457 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */
3458 
3459     /*
3460      *
3461      * Part 2: For key exchanges involving the server signing the
3462      *         exchange parameters, compute and add the signature here.
3463      *
3464      */
3465 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3466     if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
3467     {
3468         size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed;
3469         size_t hashlen = 0;
3470 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3471         unsigned char hash[PSA_HASH_MAX_SIZE];
3472 #else
3473         unsigned char hash[MBEDTLS_MD_MAX_SIZE];
3474 #endif
3475         int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3476 
3477         /*
3478          * 2.1: Choose hash algorithm:
3479          * A: For TLS 1.2, obey signature-hash-algorithm extension
3480          *    to choose appropriate hash.
3481          * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1
3482          *    (RFC 4492, Sec. 5.4)
3483          * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3)
3484          */
3485 
3486         mbedtls_md_type_t md_alg;
3487 
3488 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3489         mbedtls_pk_type_t sig_alg =
3490             mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
3491         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
3492         {
3493             /* A: For TLS 1.2, obey signature-hash-algorithm extension
3494              *    (RFC 5246, Sec. 7.4.1.4.1). */
3495             if( sig_alg == MBEDTLS_PK_NONE ||
3496                 ( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs,
3497                                                           sig_alg ) ) == MBEDTLS_MD_NONE )
3498             {
3499                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3500                 /* (... because we choose a cipher suite
3501                  *      only if there is a matching hash.) */
3502                 return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3503             }
3504         }
3505         else
3506 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3507 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3508     defined(MBEDTLS_SSL_PROTO_TLS1_1)
3509         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
3510         {
3511             /* B: Default hash SHA1 */
3512             md_alg = MBEDTLS_MD_SHA1;
3513         }
3514         else
3515 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
3516           MBEDTLS_SSL_PROTO_TLS1_1 */
3517         {
3518             /* C: MD5 + SHA1 */
3519             md_alg = MBEDTLS_MD_NONE;
3520         }
3521 
3522         MBEDTLS_SSL_DEBUG_MSG( 3, ( "pick hash algorithm %u for signing", (unsigned) md_alg ) );
3523 
3524         /*
3525          * 2.2: Compute the hash to be signed
3526          */
3527 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3528     defined(MBEDTLS_SSL_PROTO_TLS1_1)
3529         if( md_alg == MBEDTLS_MD_NONE )
3530         {
3531             hashlen = 36;
3532             ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash,
3533                                                            dig_signed,
3534                                                            dig_signed_len );
3535             if( ret != 0 )
3536                 return( ret );
3537         }
3538         else
3539 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
3540           MBEDTLS_SSL_PROTO_TLS1_1 */
3541 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3542     defined(MBEDTLS_SSL_PROTO_TLS1_2)
3543         if( md_alg != MBEDTLS_MD_NONE )
3544         {
3545             ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,
3546                                                           dig_signed,
3547                                                           dig_signed_len,
3548                                                           md_alg );
3549             if( ret != 0 )
3550                 return( ret );
3551         }
3552         else
3553 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
3554           MBEDTLS_SSL_PROTO_TLS1_2 */
3555         {
3556             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3557             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3558         }
3559 
3560         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen );
3561 
3562         /*
3563          * 2.3: Compute and add the signature
3564          */
3565 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3566         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
3567         {
3568             /*
3569              * For TLS 1.2, we need to specify signature and hash algorithm
3570              * explicitly through a prefix to the signature.
3571              *
3572              * struct {
3573              *    HashAlgorithm hash;
3574              *    SignatureAlgorithm signature;
3575              * } SignatureAndHashAlgorithm;
3576              *
3577              * struct {
3578              *    SignatureAndHashAlgorithm algorithm;
3579              *    opaque signature<0..2^16-1>;
3580              * } DigitallySigned;
3581              *
3582              */
3583 
3584             ssl->out_msg[ssl->out_msglen++] =
3585                 mbedtls_ssl_hash_from_md_alg( md_alg );
3586             ssl->out_msg[ssl->out_msglen++] =
3587                 mbedtls_ssl_sig_from_pk_alg( sig_alg );
3588         }
3589 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3590 
3591 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3592         if( ssl->conf->f_async_sign_start != NULL )
3593         {
3594             ret = ssl->conf->f_async_sign_start( ssl,
3595                                                  mbedtls_ssl_own_cert( ssl ),
3596                                                  md_alg, hash, hashlen );
3597             switch( ret )
3598             {
3599             case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3600                 /* act as if f_async_sign was null */
3601                 break;
3602             case 0:
3603                 ssl->handshake->async_in_progress = 1;
3604                 return( ssl_resume_server_key_exchange( ssl, signature_len ) );
3605             case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3606                 ssl->handshake->async_in_progress = 1;
3607                 return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
3608             default:
3609                 MBEDTLS_SSL_DEBUG_RET( 1, "f_async_sign_start", ret );
3610                 return( ret );
3611             }
3612         }
3613 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3614 
3615         if( mbedtls_ssl_own_key( ssl ) == NULL )
3616         {
3617             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key" ) );
3618             return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
3619         }
3620 
3621         /* Append the signature to ssl->out_msg, leaving 2 bytes for the
3622          * signature length which will be added in ssl_write_server_key_exchange
3623          * after the call to ssl_prepare_server_key_exchange.
3624          * ssl_write_server_key_exchange also takes care of incrementing
3625          * ssl->out_msglen. */
3626         if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ),
3627                                      md_alg, hash, hashlen,
3628                                      ssl->out_msg + ssl->out_msglen + 2,
3629                                      signature_len,
3630                                      ssl->conf->f_rng,
3631                                      ssl->conf->p_rng ) ) != 0 )
3632         {
3633             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
3634             return( ret );
3635         }
3636     }
3637 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3638 
3639     return( 0 );
3640 }
3641 
3642 /* Prepare the ServerKeyExchange message and send it. For ciphersuites
3643  * that do not include a ServerKeyExchange message, do nothing. Either
3644  * way, if successful, move on to the next step in the SSL state
3645  * machine. */
ssl_write_server_key_exchange(mbedtls_ssl_context * ssl)3646 static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl )
3647 {
3648     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3649     size_t signature_len = 0;
3650 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3651     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3652                             ssl->handshake->ciphersuite_info;
3653 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3654 
3655     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server key exchange" ) );
3656 
3657 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3658     /* Extract static ECDH parameters and abort if ServerKeyExchange
3659      * is not needed. */
3660     if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) )
3661     {
3662         /* For suites involving ECDH, extract DH parameters
3663          * from certificate at this point. */
3664 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED)
3665         if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) )
3666         {
3667             ssl_get_ecdh_params_from_cert( ssl );
3668         }
3669 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */
3670 
3671         /* Key exchanges not involving ephemeral keys don't use
3672          * ServerKeyExchange, so end here. */
3673         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write server key exchange" ) );
3674         ssl->state++;
3675         return( 0 );
3676     }
3677 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3678 
3679 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
3680     defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3681     /* If we have already prepared the message and there is an ongoing
3682      * signature operation, resume signing. */
3683     if( ssl->handshake->async_in_progress != 0 )
3684     {
3685         MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming signature operation" ) );
3686         ret = ssl_resume_server_key_exchange( ssl, &signature_len );
3687     }
3688     else
3689 #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
3690           defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
3691     {
3692         /* ServerKeyExchange is needed. Prepare the message. */
3693         ret = ssl_prepare_server_key_exchange( ssl, &signature_len );
3694     }
3695 
3696     if( ret != 0 )
3697     {
3698         /* If we're starting to write a new message, set ssl->out_msglen
3699          * to 0. But if we're resuming after an asynchronous message,
3700          * out_msglen is the amount of data written so far and mst be
3701          * preserved. */
3702         if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
3703             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange (pending)" ) );
3704         else
3705             ssl->out_msglen = 0;
3706         return( ret );
3707     }
3708 
3709     /* If there is a signature, write its length.
3710      * ssl_prepare_server_key_exchange already wrote the signature
3711      * itself at its proper place in the output buffer. */
3712 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3713     if( signature_len != 0 )
3714     {
3715         ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_1( signature_len );
3716         ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_0( signature_len );
3717 
3718         MBEDTLS_SSL_DEBUG_BUF( 3, "my signature",
3719                                ssl->out_msg + ssl->out_msglen,
3720                                signature_len );
3721 
3722         /* Skip over the already-written signature */
3723         ssl->out_msglen += signature_len;
3724     }
3725 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3726 
3727     /* Add header and send. */
3728     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3729     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
3730 
3731     ssl->state++;
3732 
3733     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
3734     {
3735         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
3736         return( ret );
3737     }
3738 
3739     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange" ) );
3740     return( 0 );
3741 }
3742 
ssl_write_server_hello_done(mbedtls_ssl_context * ssl)3743 static int ssl_write_server_hello_done( mbedtls_ssl_context *ssl )
3744 {
3745     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3746 
3747     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello done" ) );
3748 
3749     ssl->out_msglen  = 4;
3750     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3751     ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
3752 
3753     ssl->state++;
3754 
3755 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3756     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3757         mbedtls_ssl_send_flight_completed( ssl );
3758 #endif
3759 
3760     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
3761     {
3762         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
3763         return( ret );
3764     }
3765 
3766 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3767     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3768         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
3769     {
3770         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
3771         return( ret );
3772     }
3773 #endif /* MBEDTLS_SSL_PROTO_DTLS */
3774 
3775     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello done" ) );
3776 
3777     return( 0 );
3778 }
3779 
3780 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
3781     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
ssl_parse_client_dh_public(mbedtls_ssl_context * ssl,unsigned char ** p,const unsigned char * end)3782 static int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p,
3783                                        const unsigned char *end )
3784 {
3785     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3786     size_t n;
3787 
3788     /*
3789      * Receive G^Y mod P, premaster = (G^Y)^X mod P
3790      */
3791     if( *p + 2 > end )
3792     {
3793         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
3794         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
3795     }
3796 
3797     n = ( (*p)[0] << 8 ) | (*p)[1];
3798     *p += 2;
3799 
3800     if( *p + n > end )
3801     {
3802         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
3803         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
3804     }
3805 
3806     if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 )
3807     {
3808         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_read_public", ret );
3809         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
3810     }
3811 
3812     *p += n;
3813 
3814     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
3815 
3816     return( ret );
3817 }
3818 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
3819           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3820 
3821 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
3822     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3823 
3824 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
ssl_resume_decrypt_pms(mbedtls_ssl_context * ssl,unsigned char * peer_pms,size_t * peer_pmslen,size_t peer_pmssize)3825 static int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl,
3826                                    unsigned char *peer_pms,
3827                                    size_t *peer_pmslen,
3828                                    size_t peer_pmssize )
3829 {
3830     int ret = ssl->conf->f_async_resume( ssl,
3831                                          peer_pms, peer_pmslen, peer_pmssize );
3832     if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
3833     {
3834         ssl->handshake->async_in_progress = 0;
3835         mbedtls_ssl_set_async_operation_data( ssl, NULL );
3836     }
3837     MBEDTLS_SSL_DEBUG_RET( 2, "ssl_decrypt_encrypted_pms", ret );
3838     return( ret );
3839 }
3840 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3841 
ssl_decrypt_encrypted_pms(mbedtls_ssl_context * ssl,const unsigned char * p,const unsigned char * end,unsigned char * peer_pms,size_t * peer_pmslen,size_t peer_pmssize)3842 static int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl,
3843                                       const unsigned char *p,
3844                                       const unsigned char *end,
3845                                       unsigned char *peer_pms,
3846                                       size_t *peer_pmslen,
3847                                       size_t peer_pmssize )
3848 {
3849     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3850     mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl );
3851     mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk;
3852     size_t len = mbedtls_pk_get_len( public_key );
3853 
3854 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3855     /* If we have already started decoding the message and there is an ongoing
3856      * decryption operation, resume signing. */
3857     if( ssl->handshake->async_in_progress != 0 )
3858     {
3859         MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming decryption operation" ) );
3860         return( ssl_resume_decrypt_pms( ssl,
3861                                         peer_pms, peer_pmslen, peer_pmssize ) );
3862     }
3863 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3864 
3865     /*
3866      * Prepare to decrypt the premaster using own private RSA key
3867      */
3868 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3869     defined(MBEDTLS_SSL_PROTO_TLS1_2)
3870     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 )
3871     {
3872         if ( p + 2 > end )
3873         {
3874             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
3875             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
3876         }
3877         if( *p++ != MBEDTLS_BYTE_1( len ) ||
3878             *p++ != MBEDTLS_BYTE_0( len ) )
3879         {
3880             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
3881             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
3882         }
3883     }
3884 #endif
3885 
3886     if( p + len != end )
3887     {
3888         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
3889         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
3890     }
3891 
3892     /*
3893      * Decrypt the premaster secret
3894      */
3895 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3896     if( ssl->conf->f_async_decrypt_start != NULL )
3897     {
3898         ret = ssl->conf->f_async_decrypt_start( ssl,
3899                                                 mbedtls_ssl_own_cert( ssl ),
3900                                                 p, len );
3901         switch( ret )
3902         {
3903         case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3904             /* act as if f_async_decrypt_start was null */
3905             break;
3906         case 0:
3907             ssl->handshake->async_in_progress = 1;
3908             return( ssl_resume_decrypt_pms( ssl,
3909                                             peer_pms,
3910                                             peer_pmslen,
3911                                             peer_pmssize ) );
3912         case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3913             ssl->handshake->async_in_progress = 1;
3914             return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS );
3915         default:
3916             MBEDTLS_SSL_DEBUG_RET( 1, "f_async_decrypt_start", ret );
3917             return( ret );
3918         }
3919     }
3920 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3921 
3922     if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) )
3923     {
3924         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no RSA private key" ) );
3925         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
3926     }
3927 
3928     ret = mbedtls_pk_decrypt( private_key, p, len,
3929                               peer_pms, peer_pmslen, peer_pmssize,
3930                               ssl->conf->f_rng, ssl->conf->p_rng );
3931     return( ret );
3932 }
3933 
ssl_parse_encrypted_pms(mbedtls_ssl_context * ssl,const unsigned char * p,const unsigned char * end,size_t pms_offset)3934 static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl,
3935                                     const unsigned char *p,
3936                                     const unsigned char *end,
3937                                     size_t pms_offset )
3938 {
3939     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3940     unsigned char *pms = ssl->handshake->premaster + pms_offset;
3941     unsigned char ver[2];
3942     unsigned char fake_pms[48], peer_pms[48];
3943     unsigned char mask;
3944     size_t i, peer_pmslen;
3945     unsigned int diff;
3946 
3947     /* In case of a failure in decryption, the decryption may write less than
3948      * 2 bytes of output, but we always read the first two bytes. It doesn't
3949      * matter in the end because diff will be nonzero in that case due to
3950      * ret being nonzero, and we only care whether diff is 0.
3951      * But do initialize peer_pms and peer_pmslen for robustness anyway. This
3952      * also makes memory analyzers happy (don't access uninitialized memory,
3953      * even if it's an unsigned char). */
3954     peer_pms[0] = peer_pms[1] = ~0;
3955     peer_pmslen = 0;
3956 
3957     ret = ssl_decrypt_encrypted_pms( ssl, p, end,
3958                                      peer_pms,
3959                                      &peer_pmslen,
3960                                      sizeof( peer_pms ) );
3961 
3962 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3963     if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS )
3964         return( ret );
3965 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3966 
3967     mbedtls_ssl_write_version( ssl->handshake->max_major_ver,
3968                                ssl->handshake->max_minor_ver,
3969                                ssl->conf->transport, ver );
3970 
3971     /* Avoid data-dependent branches while checking for invalid
3972      * padding, to protect against timing-based Bleichenbacher-type
3973      * attacks. */
3974     diff  = (unsigned int) ret;
3975     diff |= peer_pmslen ^ 48;
3976     diff |= peer_pms[0] ^ ver[0];
3977     diff |= peer_pms[1] ^ ver[1];
3978 
3979     /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */
3980     mask = mbedtls_ct_uint_mask( diff );
3981 
3982     /*
3983      * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding
3984      * must not cause the connection to end immediately; instead, send a
3985      * bad_record_mac later in the handshake.
3986      * To protect against timing-based variants of the attack, we must
3987      * not have any branch that depends on whether the decryption was
3988      * successful. In particular, always generate the fake premaster secret,
3989      * regardless of whether it will ultimately influence the output or not.
3990      */
3991     ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) );
3992     if( ret != 0 )
3993     {
3994         /* It's ok to abort on an RNG failure, since this does not reveal
3995          * anything about the RSA decryption. */
3996         return( ret );
3997     }
3998 
3999 #if defined(MBEDTLS_SSL_DEBUG_ALL)
4000     if( diff != 0 )
4001         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
4002 #endif
4003 
4004     if( sizeof( ssl->handshake->premaster ) < pms_offset ||
4005         sizeof( ssl->handshake->premaster ) - pms_offset < 48 )
4006     {
4007         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4008         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4009     }
4010     ssl->handshake->pmslen = 48;
4011 
4012     /* Set pms to either the true or the fake PMS, without
4013      * data-dependent branches. */
4014     for( i = 0; i < ssl->handshake->pmslen; i++ )
4015         pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] );
4016 
4017     return( 0 );
4018 }
4019 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
4020           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
4021 
4022 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
ssl_parse_client_psk_identity(mbedtls_ssl_context * ssl,unsigned char ** p,const unsigned char * end)4023 static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p,
4024                                           const unsigned char *end )
4025 {
4026     int ret = 0;
4027     uint16_t n;
4028 
4029     if( ssl_conf_has_psk_or_cb( ssl->conf ) == 0 )
4030     {
4031         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) );
4032         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
4033     }
4034 
4035     /*
4036      * Receive client pre-shared key identity name
4037      */
4038     if( end - *p < 2 )
4039     {
4040         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
4041         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
4042     }
4043 
4044     n = ( (*p)[0] << 8 ) | (*p)[1];
4045     *p += 2;
4046 
4047     if( n == 0 || n > end - *p )
4048     {
4049         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
4050         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
4051     }
4052 
4053     if( ssl->conf->f_psk != NULL )
4054     {
4055         if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
4056             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
4057     }
4058     else
4059     {
4060         /* Identity is not a big secret since clients send it in the clear,
4061          * but treat it carefully anyway, just in case */
4062         if( n != ssl->conf->psk_identity_len ||
4063             mbedtls_ct_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
4064         {
4065             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
4066         }
4067     }
4068 
4069     if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
4070     {
4071         MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
4072         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4073                                         MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY );
4074         return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
4075     }
4076 
4077     *p += n;
4078 
4079     return( 0 );
4080 }
4081 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
4082 
ssl_parse_client_key_exchange(mbedtls_ssl_context * ssl)4083 static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl )
4084 {
4085     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4086     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
4087     unsigned char *p, *end;
4088 
4089     ciphersuite_info = ssl->handshake->ciphersuite_info;
4090 
4091     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) );
4092 
4093 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
4094     ( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
4095       defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) )
4096     if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
4097           ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) &&
4098         ( ssl->handshake->async_in_progress != 0 ) )
4099     {
4100         /* We've already read a record and there is an asynchronous
4101          * operation in progress to decrypt it. So skip reading the
4102          * record. */
4103         MBEDTLS_SSL_DEBUG_MSG( 3, ( "will resume decryption of previously-read record" ) );
4104     }
4105     else
4106 #endif
4107     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
4108     {
4109         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4110         return( ret );
4111     }
4112 
4113     p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
4114     end = ssl->in_msg + ssl->in_hslen;
4115 
4116     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
4117     {
4118         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
4119         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
4120     }
4121 
4122     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE )
4123     {
4124         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) );
4125         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
4126     }
4127 
4128 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
4129     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
4130     {
4131         if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
4132         {
4133             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
4134             return( ret );
4135         }
4136 
4137         if( p != end )
4138         {
4139             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
4140             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
4141         }
4142 
4143         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
4144                                       ssl->handshake->premaster,
4145                                       MBEDTLS_PREMASTER_SIZE,
4146                                      &ssl->handshake->pmslen,
4147                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
4148         {
4149             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
4150             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
4151         }
4152 
4153         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
4154     }
4155     else
4156 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
4157 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
4158     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
4159     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
4160     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
4161     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
4162         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
4163         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
4164         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
4165     {
4166         if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
4167                                       p, end - p) ) != 0 )
4168         {
4169             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
4170             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
4171         }
4172 
4173         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
4174                                 MBEDTLS_DEBUG_ECDH_QP );
4175 
4176         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
4177                                       &ssl->handshake->pmslen,
4178                                        ssl->handshake->premaster,
4179                                        MBEDTLS_MPI_MAX_SIZE,
4180                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
4181         {
4182             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
4183             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS );
4184         }
4185 
4186         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
4187                                 MBEDTLS_DEBUG_ECDH_Z );
4188     }
4189     else
4190 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
4191           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
4192           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
4193           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
4194 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
4195     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
4196     {
4197         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
4198         {
4199             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
4200             return( ret );
4201         }
4202 
4203         if( p != end )
4204         {
4205             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
4206             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
4207         }
4208 
4209 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4210         /* For opaque PSKs, we perform the PSK-to-MS derivation atomatically
4211          * and skip the intermediate PMS. */
4212         if( ssl_use_opaque_psk( ssl ) == 1 )
4213             MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) );
4214         else
4215 #endif /* MBEDTLS_USE_PSA_CRYPTO */
4216         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
4217                         ciphersuite_info->key_exchange ) ) != 0 )
4218         {
4219             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
4220             return( ret );
4221         }
4222     }
4223     else
4224 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
4225 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
4226     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
4227     {
4228 #if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
4229         if ( ssl->handshake->async_in_progress != 0 )
4230         {
4231             /* There is an asynchronous operation in progress to
4232              * decrypt the encrypted premaster secret, so skip
4233              * directly to resuming this operation. */
4234             MBEDTLS_SSL_DEBUG_MSG( 3, ( "PSK identity already parsed" ) );
4235             /* Update p to skip the PSK identity. ssl_parse_encrypted_pms
4236              * won't actually use it, but maintain p anyway for robustness. */
4237             p += ssl->conf->psk_identity_len + 2;
4238         }
4239         else
4240 #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
4241         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
4242         {
4243             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
4244             return( ret );
4245         }
4246 
4247 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4248         /* Opaque PSKs are currently only supported for PSK-only. */
4249         if( ssl_use_opaque_psk( ssl ) == 1 )
4250             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
4251 #endif
4252 
4253         if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 )
4254         {
4255             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret );
4256             return( ret );
4257         }
4258 
4259         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
4260                         ciphersuite_info->key_exchange ) ) != 0 )
4261         {
4262             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
4263             return( ret );
4264         }
4265     }
4266     else
4267 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
4268 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
4269     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
4270     {
4271         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
4272         {
4273             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
4274             return( ret );
4275         }
4276         if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 )
4277         {
4278             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret );
4279             return( ret );
4280         }
4281 
4282 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4283         /* Opaque PSKs are currently only supported for PSK-only. */
4284         if( ssl_use_opaque_psk( ssl ) == 1 )
4285             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
4286 #endif
4287 
4288         if( p != end )
4289         {
4290             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) );
4291             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
4292         }
4293 
4294         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
4295                         ciphersuite_info->key_exchange ) ) != 0 )
4296         {
4297             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
4298             return( ret );
4299         }
4300     }
4301     else
4302 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
4303 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
4304     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
4305     {
4306         if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 )
4307         {
4308             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret );
4309             return( ret );
4310         }
4311 
4312         if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx,
4313                                        p, end - p ) ) != 0 )
4314         {
4315             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret );
4316             return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP );
4317         }
4318 
4319 #if defined(MBEDTLS_USE_PSA_CRYPTO)
4320         /* Opaque PSKs are currently only supported for PSK-only. */
4321         if( ssl_use_opaque_psk( ssl ) == 1 )
4322             return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
4323 #endif
4324 
4325         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
4326                                 MBEDTLS_DEBUG_ECDH_QP );
4327 
4328         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
4329                         ciphersuite_info->key_exchange ) ) != 0 )
4330         {
4331             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
4332             return( ret );
4333         }
4334     }
4335     else
4336 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
4337 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
4338     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
4339     {
4340         if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 )
4341         {
4342             MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_parse_encrypted_pms_secret" ), ret );
4343             return( ret );
4344         }
4345     }
4346     else
4347 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
4348 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4349     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4350     {
4351         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
4352                                               p, end - p );
4353         if( ret != 0 )
4354         {
4355             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
4356             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
4357         }
4358 
4359         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
4360                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
4361                 ssl->conf->f_rng, ssl->conf->p_rng );
4362         if( ret != 0 )
4363         {
4364             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
4365             return( ret );
4366         }
4367     }
4368     else
4369 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4370     {
4371         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4372         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4373     }
4374 
4375     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
4376     {
4377         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
4378         return( ret );
4379     }
4380 
4381     ssl->state++;
4382 
4383     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) );
4384 
4385     return( 0 );
4386 }
4387 
4388 #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
ssl_parse_certificate_verify(mbedtls_ssl_context * ssl)4389 static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
4390 {
4391     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4392         ssl->handshake->ciphersuite_info;
4393 
4394     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
4395 
4396     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
4397     {
4398         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
4399         ssl->state++;
4400         return( 0 );
4401     }
4402 
4403     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4404     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4405 }
4406 #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
ssl_parse_certificate_verify(mbedtls_ssl_context * ssl)4407 static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl )
4408 {
4409     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4410     size_t i, sig_len;
4411     unsigned char hash[48];
4412     unsigned char *hash_start = hash;
4413     size_t hashlen;
4414 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4415     mbedtls_pk_type_t pk_alg;
4416 #endif
4417     mbedtls_md_type_t md_alg;
4418     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4419         ssl->handshake->ciphersuite_info;
4420     mbedtls_pk_context * peer_pk;
4421 
4422     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) );
4423 
4424     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
4425     {
4426         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
4427         ssl->state++;
4428         return( 0 );
4429     }
4430 
4431 #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4432     if( ssl->session_negotiate->peer_cert == NULL )
4433     {
4434         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
4435         ssl->state++;
4436         return( 0 );
4437     }
4438 #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4439     if( ssl->session_negotiate->peer_cert_digest == NULL )
4440     {
4441         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) );
4442         ssl->state++;
4443         return( 0 );
4444     }
4445 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4446 
4447     /* Read the message without adding it to the checksum */
4448     ret = mbedtls_ssl_read_record( ssl, 0 /* no checksum update */ );
4449     if( 0 != ret )
4450     {
4451         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record" ), ret );
4452         return( ret );
4453     }
4454 
4455     ssl->state++;
4456 
4457     /* Process the message contents */
4458     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
4459         ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY )
4460     {
4461         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
4462         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
4463     }
4464 
4465     i = mbedtls_ssl_hs_hdr_len( ssl );
4466 
4467 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4468     peer_pk = &ssl->handshake->peer_pubkey;
4469 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4470     if( ssl->session_negotiate->peer_cert == NULL )
4471     {
4472         /* Should never happen */
4473         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4474     }
4475     peer_pk = &ssl->session_negotiate->peer_cert->pk;
4476 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4477 
4478     /*
4479      *  struct {
4480      *     SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only
4481      *     opaque signature<0..2^16-1>;
4482      *  } DigitallySigned;
4483      */
4484 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4485     defined(MBEDTLS_SSL_PROTO_TLS1_1)
4486     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
4487     {
4488         md_alg = MBEDTLS_MD_NONE;
4489         hashlen = 36;
4490 
4491         /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */
4492         if( mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECDSA ) )
4493         {
4494             hash_start += 16;
4495             hashlen -= 16;
4496             md_alg = MBEDTLS_MD_SHA1;
4497         }
4498     }
4499     else
4500 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 ||
4501           MBEDTLS_SSL_PROTO_TLS1_1 */
4502 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4503     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
4504     {
4505         if( i + 2 > ssl->in_hslen )
4506         {
4507             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
4508             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
4509         }
4510 
4511         /*
4512          * Hash
4513          */
4514         md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] );
4515 
4516         if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) )
4517         {
4518             MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
4519                                 " for verify message" ) );
4520             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
4521         }
4522 
4523 #if !defined(MBEDTLS_MD_SHA1)
4524         if( MBEDTLS_MD_SHA1 == md_alg )
4525             hash_start += 16;
4526 #endif
4527 
4528         /* Info from md_alg will be used instead */
4529         hashlen = 0;
4530 
4531         i++;
4532 
4533         /*
4534          * Signature
4535          */
4536         if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) )
4537                         == MBEDTLS_PK_NONE )
4538         {
4539             MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg"
4540                                 " for verify message" ) );
4541             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
4542         }
4543 
4544         /*
4545          * Check the certificate's key type matches the signature alg
4546          */
4547         if( !mbedtls_pk_can_do( peer_pk, pk_alg ) )
4548         {
4549             MBEDTLS_SSL_DEBUG_MSG( 1, ( "sig_alg doesn't match cert key" ) );
4550             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
4551         }
4552 
4553         i++;
4554     }
4555     else
4556 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4557     {
4558         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4559         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4560     }
4561 
4562     if( i + 2 > ssl->in_hslen )
4563     {
4564         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
4565         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
4566     }
4567 
4568     sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1];
4569     i += 2;
4570 
4571     if( i + sig_len != ssl->in_hslen )
4572     {
4573         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) );
4574         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY );
4575     }
4576 
4577     /* Calculate hash and verify signature */
4578     {
4579         size_t dummy_hlen;
4580         ssl->handshake->calc_verify( ssl, hash, &dummy_hlen );
4581     }
4582 
4583     if( ( ret = mbedtls_pk_verify( peer_pk,
4584                            md_alg, hash_start, hashlen,
4585                            ssl->in_msg + i, sig_len ) ) != 0 )
4586     {
4587         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
4588         return( ret );
4589     }
4590 
4591     mbedtls_ssl_update_handshake_status( ssl );
4592 
4593     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) );
4594 
4595     return( ret );
4596 }
4597 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4598 
4599 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_new_session_ticket(mbedtls_ssl_context * ssl)4600 static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl )
4601 {
4602     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4603     size_t tlen;
4604     uint32_t lifetime;
4605 
4606     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) );
4607 
4608     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4609     ssl->out_msg[0]  = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;
4610 
4611     /*
4612      * struct {
4613      *     uint32 ticket_lifetime_hint;
4614      *     opaque ticket<0..2^16-1>;
4615      * } NewSessionTicket;
4616      *
4617      * 4  .  7   ticket_lifetime_hint (0 = unspecified)
4618      * 8  .  9   ticket_len (n)
4619      * 10 .  9+n ticket content
4620      */
4621 
4622     if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket,
4623                                 ssl->session_negotiate,
4624                                 ssl->out_msg + 10,
4625                                 ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
4626                                 &tlen, &lifetime ) ) != 0 )
4627     {
4628         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret );
4629         tlen = 0;
4630     }
4631 
4632     MBEDTLS_PUT_UINT32_BE( lifetime, ssl->out_msg, 4 );
4633     MBEDTLS_PUT_UINT16_BE( tlen, ssl->out_msg, 8 );
4634     ssl->out_msglen = 10 + tlen;
4635 
4636     /*
4637      * Morally equivalent to updating ssl->state, but NewSessionTicket and
4638      * ChangeCipherSpec share the same state.
4639      */
4640     ssl->handshake->new_session_ticket = 0;
4641 
4642     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
4643     {
4644         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
4645         return( ret );
4646     }
4647 
4648     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) );
4649 
4650     return( 0 );
4651 }
4652 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
4653 
4654 /*
4655  * SSL handshake -- server side -- single step
4656  */
mbedtls_ssl_handshake_server_step(mbedtls_ssl_context * ssl)4657 int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl )
4658 {
4659     int ret = 0;
4660 
4661     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
4662         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4663 
4664     MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) );
4665 
4666     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
4667         return( ret );
4668 
4669 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4670     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4671         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
4672     {
4673         if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
4674             return( ret );
4675     }
4676 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4677 
4678     switch( ssl->state )
4679     {
4680         case MBEDTLS_SSL_HELLO_REQUEST:
4681             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
4682             break;
4683 
4684         /*
4685          *  <==   ClientHello
4686          */
4687         case MBEDTLS_SSL_CLIENT_HELLO:
4688             ret = ssl_parse_client_hello( ssl );
4689             break;
4690 
4691 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4692         case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
4693             return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED );
4694 #endif
4695 
4696         /*
4697          *  ==>   ServerHello
4698          *        Certificate
4699          *      ( ServerKeyExchange  )
4700          *      ( CertificateRequest )
4701          *        ServerHelloDone
4702          */
4703         case MBEDTLS_SSL_SERVER_HELLO:
4704             ret = ssl_write_server_hello( ssl );
4705             break;
4706 
4707         case MBEDTLS_SSL_SERVER_CERTIFICATE:
4708             ret = mbedtls_ssl_write_certificate( ssl );
4709             break;
4710 
4711         case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
4712             ret = ssl_write_server_key_exchange( ssl );
4713             break;
4714 
4715         case MBEDTLS_SSL_CERTIFICATE_REQUEST:
4716             ret = ssl_write_certificate_request( ssl );
4717             break;
4718 
4719         case MBEDTLS_SSL_SERVER_HELLO_DONE:
4720             ret = ssl_write_server_hello_done( ssl );
4721             break;
4722 
4723         /*
4724          *  <== ( Certificate/Alert  )
4725          *        ClientKeyExchange
4726          *      ( CertificateVerify  )
4727          *        ChangeCipherSpec
4728          *        Finished
4729          */
4730         case MBEDTLS_SSL_CLIENT_CERTIFICATE:
4731             ret = mbedtls_ssl_parse_certificate( ssl );
4732             break;
4733 
4734         case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
4735             ret = ssl_parse_client_key_exchange( ssl );
4736             break;
4737 
4738         case MBEDTLS_SSL_CERTIFICATE_VERIFY:
4739             ret = ssl_parse_certificate_verify( ssl );
4740             break;
4741 
4742         case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
4743             ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
4744             break;
4745 
4746         case MBEDTLS_SSL_CLIENT_FINISHED:
4747             ret = mbedtls_ssl_parse_finished( ssl );
4748             break;
4749 
4750         /*
4751          *  ==> ( NewSessionTicket )
4752          *        ChangeCipherSpec
4753          *        Finished
4754          */
4755         case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
4756 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
4757             if( ssl->handshake->new_session_ticket != 0 )
4758                 ret = ssl_write_new_session_ticket( ssl );
4759             else
4760 #endif
4761                 ret = mbedtls_ssl_write_change_cipher_spec( ssl );
4762             break;
4763 
4764         case MBEDTLS_SSL_SERVER_FINISHED:
4765             ret = mbedtls_ssl_write_finished( ssl );
4766             break;
4767 
4768         case MBEDTLS_SSL_FLUSH_BUFFERS:
4769             MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
4770             ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
4771             break;
4772 
4773         case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
4774             mbedtls_ssl_handshake_wrapup( ssl );
4775             break;
4776 
4777         default:
4778             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
4779             return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4780     }
4781 
4782     return( ret );
4783 }
4784 #endif /* MBEDTLS_SSL_SRV_C */
4785