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