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