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