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