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