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