xref: /reactos/dll/3rdparty/mbedtls/ssl_cli.c (revision 019f21ee)
1 /*
2  *  SSLv3/TLSv1 client-side functions
3  *
4  *  Copyright (C) 2006-2015, ARM Limited, All Rights Reserved
5  *  SPDX-License-Identifier: GPL-2.0
6  *
7  *  This program is free software; you can redistribute it and/or modify
8  *  it under the terms of the GNU General Public License as published by
9  *  the Free Software Foundation; either version 2 of the License, or
10  *  (at your option) any later version.
11  *
12  *  This program is distributed in the hope that it will be useful,
13  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
14  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  *  GNU General Public License for more details.
16  *
17  *  You should have received a copy of the GNU General Public License along
18  *  with this program; if not, write to the Free Software Foundation, Inc.,
19  *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  *  This file is part of mbed TLS (https://tls.mbed.org)
22  */
23 
24 #if !defined(MBEDTLS_CONFIG_FILE)
25 #include "mbedtls/config.h"
26 #else
27 #include MBEDTLS_CONFIG_FILE
28 #endif
29 
30 #if defined(MBEDTLS_SSL_CLI_C)
31 
32 #if defined(MBEDTLS_PLATFORM_C)
33 #include "mbedtls/platform.h"
34 #else
35 #include <stdlib.h>
36 #define mbedtls_calloc    calloc
37 #define mbedtls_free      free
38 #endif
39 
40 #include "mbedtls/debug.h"
41 #include "mbedtls/ssl.h"
42 #include "mbedtls/ssl_internal.h"
43 
44 #include <string.h>
45 
46 #include <stdint.h>
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 */
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_SERVER_NAME_INDICATION)
60 static void ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
61                                     unsigned char *buf,
62                                     size_t *olen )
63 {
64     unsigned char *p = buf;
65     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
66     size_t hostname_len;
67 
68     *olen = 0;
69 
70     if( ssl->hostname == NULL )
71         return;
72 
73     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding server name extension: %s",
74                    ssl->hostname ) );
75 
76     hostname_len = strlen( ssl->hostname );
77 
78     if( end < p || (size_t)( end - p ) < hostname_len + 9 )
79     {
80         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
81         return;
82     }
83 
84     /*
85      * Sect. 3, RFC 6066 (TLS Extensions Definitions)
86      *
87      * In order to provide any of the server names, clients MAY include an
88      * extension of type "server_name" in the (extended) client hello. The
89      * "extension_data" field of this extension SHALL contain
90      * "ServerNameList" where:
91      *
92      * struct {
93      *     NameType name_type;
94      *     select (name_type) {
95      *         case host_name: HostName;
96      *     } name;
97      * } ServerName;
98      *
99      * enum {
100      *     host_name(0), (255)
101      * } NameType;
102      *
103      * opaque HostName<1..2^16-1>;
104      *
105      * struct {
106      *     ServerName server_name_list<1..2^16-1>
107      * } ServerNameList;
108      *
109      */
110     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
111     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME      ) & 0xFF );
112 
113     *p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
114     *p++ = (unsigned char)( ( (hostname_len + 5)      ) & 0xFF );
115 
116     *p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
117     *p++ = (unsigned char)( ( (hostname_len + 3)      ) & 0xFF );
118 
119     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
120     *p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
121     *p++ = (unsigned char)( ( hostname_len      ) & 0xFF );
122 
123     memcpy( p, ssl->hostname, hostname_len );
124 
125     *olen = hostname_len + 9;
126 }
127 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
128 
129 #if defined(MBEDTLS_SSL_RENEGOTIATION)
130 static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
131                                          unsigned char *buf,
132                                          size_t *olen )
133 {
134     unsigned char *p = buf;
135     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
136 
137     *olen = 0;
138 
139     /* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
140      * initial ClientHello, in which case also adding the renegotiation
141      * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
142     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
143         return;
144 
145     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding renegotiation extension" ) );
146 
147     if( end < p || (size_t)( end - p ) < 5 + ssl->verify_data_len )
148     {
149         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
150         return;
151     }
152 
153     /*
154      * Secure renegotiation
155      */
156     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF );
157     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      ) & 0xFF );
158 
159     *p++ = 0x00;
160     *p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
161     *p++ = ssl->verify_data_len & 0xFF;
162 
163     memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
164 
165     *olen = 5 + ssl->verify_data_len;
166 }
167 #endif /* MBEDTLS_SSL_RENEGOTIATION */
168 
169 /*
170  * Only if we handle at least one key exchange that needs signatures.
171  */
172 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
173     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
174 static void ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
175                                                 unsigned char *buf,
176                                                 size_t *olen )
177 {
178     unsigned char *p = buf;
179     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
180     size_t sig_alg_len = 0;
181     const int *md;
182 #if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
183     unsigned char *sig_alg_list = buf + 6;
184 #endif
185 
186     *olen = 0;
187 
188     if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
189         return;
190 
191     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding signature_algorithms extension" ) );
192 
193     for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
194     {
195 #if defined(MBEDTLS_ECDSA_C)
196         sig_alg_len += 2;
197 #endif
198 #if defined(MBEDTLS_RSA_C)
199         sig_alg_len += 2;
200 #endif
201     }
202 
203     if( end < p || (size_t)( end - p ) < sig_alg_len + 6 )
204     {
205         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
206         return;
207     }
208 
209     /*
210      * Prepare signature_algorithms extension (TLS 1.2)
211      */
212     sig_alg_len = 0;
213 
214     for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
215     {
216 #if defined(MBEDTLS_ECDSA_C)
217         sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
218         sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
219 #endif
220 #if defined(MBEDTLS_RSA_C)
221         sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
222         sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
223 #endif
224     }
225 
226     /*
227      * enum {
228      *     none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
229      *     sha512(6), (255)
230      * } HashAlgorithm;
231      *
232      * enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
233      *   SignatureAlgorithm;
234      *
235      * struct {
236      *     HashAlgorithm hash;
237      *     SignatureAlgorithm signature;
238      * } SignatureAndHashAlgorithm;
239      *
240      * SignatureAndHashAlgorithm
241      *   supported_signature_algorithms<2..2^16-2>;
242      */
243     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
244     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG      ) & 0xFF );
245 
246     *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
247     *p++ = (unsigned char)( ( ( sig_alg_len + 2 )      ) & 0xFF );
248 
249     *p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
250     *p++ = (unsigned char)( ( sig_alg_len      ) & 0xFF );
251 
252     *olen = 6 + sig_alg_len;
253 }
254 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
255           MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED */
256 
257 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
258     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
259 static void ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
260                                                      unsigned char *buf,
261                                                      size_t *olen )
262 {
263     unsigned char *p = buf;
264     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
265     unsigned char *elliptic_curve_list = p + 6;
266     size_t elliptic_curve_len = 0;
267     const mbedtls_ecp_curve_info *info;
268 #if defined(MBEDTLS_ECP_C)
269     const mbedtls_ecp_group_id *grp_id;
270 #else
271     ((void) ssl);
272 #endif
273 
274     *olen = 0;
275 
276     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_elliptic_curves extension" ) );
277 
278 #if defined(MBEDTLS_ECP_C)
279     for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
280 #else
281     for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
282 #endif
283     {
284 #if defined(MBEDTLS_ECP_C)
285         info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
286 #endif
287         if( info == NULL )
288         {
289             MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid curve in ssl configuration" ) );
290             return;
291         }
292 
293         elliptic_curve_len += 2;
294     }
295 
296     if( end < p || (size_t)( end - p ) < 6 + elliptic_curve_len )
297     {
298         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
299         return;
300     }
301 
302     elliptic_curve_len = 0;
303 
304 #if defined(MBEDTLS_ECP_C)
305     for( grp_id = ssl->conf->curve_list; *grp_id != MBEDTLS_ECP_DP_NONE; grp_id++ )
306 #else
307     for( info = mbedtls_ecp_curve_list(); info->grp_id != MBEDTLS_ECP_DP_NONE; info++ )
308 #endif
309     {
310 #if defined(MBEDTLS_ECP_C)
311         info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
312 #endif
313         elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
314         elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
315     }
316 
317     if( elliptic_curve_len == 0 )
318         return;
319 
320     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 ) & 0xFF );
321     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES      ) & 0xFF );
322 
323     *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
324     *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 )      ) & 0xFF );
325 
326     *p++ = (unsigned char)( ( ( elliptic_curve_len     ) >> 8 ) & 0xFF );
327     *p++ = (unsigned char)( ( ( elliptic_curve_len     )      ) & 0xFF );
328 
329     *olen = 6 + elliptic_curve_len;
330 }
331 
332 static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
333                                                    unsigned char *buf,
334                                                    size_t *olen )
335 {
336     unsigned char *p = buf;
337     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
338 
339     *olen = 0;
340 
341     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding supported_point_formats extension" ) );
342 
343     if( end < p || (size_t)( end - p ) < 6 )
344     {
345         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
346         return;
347     }
348 
349     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF );
350     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS      ) & 0xFF );
351 
352     *p++ = 0x00;
353     *p++ = 2;
354 
355     *p++ = 1;
356     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
357 
358     *olen = 6;
359 }
360 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
361           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
362 
363 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
364 static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
365                                         unsigned char *buf,
366                                         size_t *olen )
367 {
368     int ret;
369     unsigned char *p = buf;
370     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
371     size_t kkpp_len;
372 
373     *olen = 0;
374 
375     /* Skip costly extension if we can't use EC J-PAKE anyway */
376     if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
377         return;
378 
379     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding ecjpake_kkpp extension" ) );
380 
381     if( end - p < 4 )
382     {
383         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
384         return;
385     }
386 
387     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
388     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP      ) & 0xFF );
389 
390     /*
391      * We may need to send ClientHello multiple times for Hello verification.
392      * We don't want to compute fresh values every time (both for performance
393      * and consistency reasons), so cache the extension content.
394      */
395     if( ssl->handshake->ecjpake_cache == NULL ||
396         ssl->handshake->ecjpake_cache_len == 0 )
397     {
398         MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
399 
400         ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
401                                         p + 2, end - p - 2, &kkpp_len,
402                                         ssl->conf->f_rng, ssl->conf->p_rng );
403         if( ret != 0 )
404         {
405             MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret );
406             return;
407         }
408 
409         ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
410         if( ssl->handshake->ecjpake_cache == NULL )
411         {
412             MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
413             return;
414         }
415 
416         memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
417         ssl->handshake->ecjpake_cache_len = kkpp_len;
418     }
419     else
420     {
421         MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
422 
423         kkpp_len = ssl->handshake->ecjpake_cache_len;
424 
425         if( (size_t)( end - p - 2 ) < kkpp_len )
426         {
427             MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
428             return;
429         }
430 
431         memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
432     }
433 
434     *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
435     *p++ = (unsigned char)( ( kkpp_len      ) & 0xFF );
436 
437     *olen = kkpp_len + 4;
438 }
439 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
440 
441 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
442 static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
443                                                unsigned char *buf,
444                                                size_t *olen )
445 {
446     unsigned char *p = buf;
447     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
448 
449     *olen = 0;
450 
451     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) {
452         return;
453     }
454 
455     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding max_fragment_length extension" ) );
456 
457     if( end < p || (size_t)( end - p ) < 5 )
458     {
459         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
460         return;
461     }
462 
463     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF );
464     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH      ) & 0xFF );
465 
466     *p++ = 0x00;
467     *p++ = 1;
468 
469     *p++ = ssl->conf->mfl_code;
470 
471     *olen = 5;
472 }
473 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
474 
475 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
476 static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
477                                           unsigned char *buf, size_t *olen )
478 {
479     unsigned char *p = buf;
480     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
481 
482     *olen = 0;
483 
484     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
485     {
486         return;
487     }
488 
489     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding truncated_hmac extension" ) );
490 
491     if( end < p || (size_t)( end - p ) < 4 )
492     {
493         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
494         return;
495     }
496 
497     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
498     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );
499 
500     *p++ = 0x00;
501     *p++ = 0x00;
502 
503     *olen = 4;
504 }
505 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
506 
507 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
508 static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
509                                        unsigned char *buf, size_t *olen )
510 {
511     unsigned char *p = buf;
512     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
513 
514     *olen = 0;
515 
516     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
517         ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
518     {
519         return;
520     }
521 
522     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding encrypt_then_mac "
523                         "extension" ) );
524 
525     if( end < p || (size_t)( end - p ) < 4 )
526     {
527         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
528         return;
529     }
530 
531     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
532     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );
533 
534     *p++ = 0x00;
535     *p++ = 0x00;
536 
537     *olen = 4;
538 }
539 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
540 
541 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
542 static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
543                                        unsigned char *buf, size_t *olen )
544 {
545     unsigned char *p = buf;
546     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
547 
548     *olen = 0;
549 
550     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
551         ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
552     {
553         return;
554     }
555 
556     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding extended_master_secret "
557                         "extension" ) );
558 
559     if( end < p || (size_t)( end - p ) < 4 )
560     {
561         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
562         return;
563     }
564 
565     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF );
566     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET      ) & 0xFF );
567 
568     *p++ = 0x00;
569     *p++ = 0x00;
570 
571     *olen = 4;
572 }
573 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
574 
575 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
576 static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
577                                           unsigned char *buf, size_t *olen )
578 {
579     unsigned char *p = buf;
580     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
581     size_t tlen = ssl->session_negotiate->ticket_len;
582 
583     *olen = 0;
584 
585     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
586     {
587         return;
588     }
589 
590     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding session ticket extension" ) );
591 
592     if( end < p || (size_t)( end - p ) < 4 + tlen )
593     {
594         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
595         return;
596     }
597 
598     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
599     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET      ) & 0xFF );
600 
601     *p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
602     *p++ = (unsigned char)( ( tlen      ) & 0xFF );
603 
604     *olen = 4;
605 
606     if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
607     {
608         return;
609     }
610 
611     MBEDTLS_SSL_DEBUG_MSG( 3, ( "sending session ticket of length %d", tlen ) );
612 
613     memcpy( p, ssl->session_negotiate->ticket, tlen );
614 
615     *olen += tlen;
616 }
617 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
618 
619 #if defined(MBEDTLS_SSL_ALPN)
620 static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
621                                 unsigned char *buf, size_t *olen )
622 {
623     unsigned char *p = buf;
624     const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_MAX_CONTENT_LEN;
625     size_t alpnlen = 0;
626     const char **cur;
627 
628     *olen = 0;
629 
630     if( ssl->conf->alpn_list == NULL )
631     {
632         return;
633     }
634 
635     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
636 
637     for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
638         alpnlen += (unsigned char)( strlen( *cur ) & 0xFF ) + 1;
639 
640     if( end < p || (size_t)( end - p ) < 6 + alpnlen )
641     {
642         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) );
643         return;
644     }
645 
646     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
647     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN      ) & 0xFF );
648 
649     /*
650      * opaque ProtocolName<1..2^8-1>;
651      *
652      * struct {
653      *     ProtocolName protocol_name_list<2..2^16-1>
654      * } ProtocolNameList;
655      */
656 
657     /* Skip writing extension and list length for now */
658     p += 4;
659 
660     for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
661     {
662         *p = (unsigned char)( strlen( *cur ) & 0xFF );
663         memcpy( p + 1, *cur, *p );
664         p += 1 + *p;
665     }
666 
667     *olen = p - buf;
668 
669     /* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
670     buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
671     buf[5] = (unsigned char)( ( ( *olen - 6 )      ) & 0xFF );
672 
673     /* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
674     buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
675     buf[3] = (unsigned char)( ( ( *olen - 4 )      ) & 0xFF );
676 }
677 #endif /* MBEDTLS_SSL_ALPN */
678 
679 /*
680  * Generate random bytes for ClientHello
681  */
682 static int ssl_generate_random( mbedtls_ssl_context *ssl )
683 {
684     int ret;
685     unsigned char *p = ssl->handshake->randbytes;
686 #if defined(MBEDTLS_HAVE_TIME)
687     mbedtls_time_t t;
688 #endif
689 
690     /*
691      * When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
692      */
693 #if defined(MBEDTLS_SSL_PROTO_DTLS)
694     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
695         ssl->handshake->verify_cookie != NULL )
696     {
697         return( 0 );
698     }
699 #endif
700 
701 #if defined(MBEDTLS_HAVE_TIME)
702     t = mbedtls_time( NULL );
703     *p++ = (unsigned char)( t >> 24 );
704     *p++ = (unsigned char)( t >> 16 );
705     *p++ = (unsigned char)( t >>  8 );
706     *p++ = (unsigned char)( t       );
707 
708     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
709 #else
710     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
711         return( ret );
712 
713     p += 4;
714 #endif /* MBEDTLS_HAVE_TIME */
715 
716     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
717         return( ret );
718 
719     return( 0 );
720 }
721 
722 /**
723  * \brief           Validate cipher suite against config in SSL context.
724  *
725  * \param suite_info    cipher suite to validate
726  * \param ssl           SSL context
727  * \param min_minor_ver Minimal minor version to accept a cipher suite
728  * \param max_minor_ver Maximal minor version to accept a cipher suite
729  *
730  * \return          0 if valid, else 1
731  */
732 static int ssl_validate_ciphersuite( const mbedtls_ssl_ciphersuite_t * suite_info,
733                                      const mbedtls_ssl_context * ssl,
734                                      int min_minor_ver, int max_minor_ver )
735 {
736     (void) ssl;
737     if( suite_info == NULL )
738         return( 1 );
739 
740     if( suite_info->min_minor_ver > max_minor_ver ||
741             suite_info->max_minor_ver < min_minor_ver )
742         return( 1 );
743 
744 #if defined(MBEDTLS_SSL_PROTO_DTLS)
745     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
746             ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
747         return( 1 );
748 #endif
749 
750 #if defined(MBEDTLS_ARC4_C)
751     if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
752             suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
753         return( 1 );
754 #endif
755 
756 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
757     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
758             mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
759         return( 1 );
760 #endif
761 
762     return( 0 );
763 }
764 
765 static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
766 {
767     int ret;
768     size_t i, n, olen, ext_len = 0;
769     unsigned char *buf;
770     unsigned char *p, *q;
771     unsigned char offer_compress;
772     const int *ciphersuites;
773     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
774 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
775     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
776     int uses_ec = 0;
777 #endif
778 
779     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
780 
781     if( ssl->conf->f_rng == NULL )
782     {
783         MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
784         return( MBEDTLS_ERR_SSL_NO_RNG );
785     }
786 
787 #if defined(MBEDTLS_SSL_RENEGOTIATION)
788     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
789 #endif
790     {
791         ssl->major_ver = ssl->conf->min_major_ver;
792         ssl->minor_ver = ssl->conf->min_minor_ver;
793     }
794 
795     if( ssl->conf->max_major_ver == 0 )
796     {
797         MBEDTLS_SSL_DEBUG_MSG( 1, ( "configured max major version is invalid, "
798                             "consider using mbedtls_ssl_config_defaults()" ) );
799         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
800     }
801 
802     /*
803      *     0  .   0   handshake type
804      *     1  .   3   handshake length
805      *     4  .   5   highest version supported
806      *     6  .   9   current UNIX time
807      *    10  .  37   random bytes
808      */
809     buf = ssl->out_msg;
810     p = buf + 4;
811 
812     mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
813                        ssl->conf->transport, p );
814     p += 2;
815 
816     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
817                    buf[4], buf[5] ) );
818 
819     if( ( ret = ssl_generate_random( ssl ) ) != 0 )
820     {
821         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
822         return( ret );
823     }
824 
825     memcpy( p, ssl->handshake->randbytes, 32 );
826     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
827     p += 32;
828 
829     /*
830      *    38  .  38   session id length
831      *    39  . 39+n  session id
832      *   39+n . 39+n  DTLS only: cookie length (1 byte)
833      *   40+n .  ..   DTSL only: cookie
834      *   ..   . ..    ciphersuitelist length (2 bytes)
835      *   ..   . ..    ciphersuitelist
836      *   ..   . ..    compression methods length (1 byte)
837      *   ..   . ..    compression methods
838      *   ..   . ..    extensions length (2 bytes)
839      *   ..   . ..    extensions
840      */
841     n = ssl->session_negotiate->id_len;
842 
843     if( n < 16 || n > 32 ||
844 #if defined(MBEDTLS_SSL_RENEGOTIATION)
845         ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
846 #endif
847         ssl->handshake->resume == 0 )
848     {
849         n = 0;
850     }
851 
852 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
853     /*
854      * RFC 5077 section 3.4: "When presenting a ticket, the client MAY
855      * generate and include a Session ID in the TLS ClientHello."
856      */
857 #if defined(MBEDTLS_SSL_RENEGOTIATION)
858     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
859 #endif
860     {
861         if( ssl->session_negotiate->ticket != NULL &&
862                 ssl->session_negotiate->ticket_len != 0 )
863         {
864             ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, 32 );
865 
866             if( ret != 0 )
867                 return( ret );
868 
869             ssl->session_negotiate->id_len = n = 32;
870         }
871     }
872 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
873 
874     *p++ = (unsigned char) n;
875 
876     for( i = 0; i < n; i++ )
877         *p++ = ssl->session_negotiate->id[i];
878 
879     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
880     MBEDTLS_SSL_DEBUG_BUF( 3,   "client hello, session id", buf + 39, n );
881 
882     /*
883      * DTLS cookie
884      */
885 #if defined(MBEDTLS_SSL_PROTO_DTLS)
886     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
887     {
888         if( ssl->handshake->verify_cookie == NULL )
889         {
890             MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
891             *p++ = 0;
892         }
893         else
894         {
895             MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
896                               ssl->handshake->verify_cookie,
897                               ssl->handshake->verify_cookie_len );
898 
899             *p++ = ssl->handshake->verify_cookie_len;
900             memcpy( p, ssl->handshake->verify_cookie,
901                        ssl->handshake->verify_cookie_len );
902             p += ssl->handshake->verify_cookie_len;
903         }
904     }
905 #endif
906 
907     /*
908      * Ciphersuite list
909      */
910     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
911 
912     /* Skip writing ciphersuite length for now */
913     n = 0;
914     q = p;
915     p += 2;
916 
917     for( i = 0; ciphersuites[i] != 0; i++ )
918     {
919         ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
920 
921         if( ssl_validate_ciphersuite( ciphersuite_info, ssl,
922                                       ssl->conf->min_minor_ver,
923                                       ssl->conf->max_minor_ver ) != 0 )
924             continue;
925 
926         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %04x",
927                                     ciphersuites[i] ) );
928 
929 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
930     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
931         uses_ec |= mbedtls_ssl_ciphersuite_uses_ec( ciphersuite_info );
932 #endif
933 
934         n++;
935         *p++ = (unsigned char)( ciphersuites[i] >> 8 );
936         *p++ = (unsigned char)( ciphersuites[i]      );
937     }
938 
939     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, got %d ciphersuites (excluding SCSVs)", n ) );
940 
941     /*
942      * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
943      */
944 #if defined(MBEDTLS_SSL_RENEGOTIATION)
945     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
946 #endif
947     {
948         MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding EMPTY_RENEGOTIATION_INFO_SCSV" ) );
949         *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
950         *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO      );
951         n++;
952     }
953 
954     /* Some versions of OpenSSL don't handle it correctly if not at end */
955 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
956     if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
957     {
958         MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
959         *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
960         *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      );
961         n++;
962     }
963 #endif
964 
965     *q++ = (unsigned char)( n >> 7 );
966     *q++ = (unsigned char)( n << 1 );
967 
968 #if defined(MBEDTLS_ZLIB_SUPPORT)
969     offer_compress = 1;
970 #else
971     offer_compress = 0;
972 #endif
973 
974     /*
975      * We don't support compression with DTLS right now: if many records come
976      * in the same datagram, uncompressing one could overwrite the next one.
977      * We don't want to add complexity for handling that case unless there is
978      * an actual need for it.
979      */
980 #if defined(MBEDTLS_SSL_PROTO_DTLS)
981     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
982         offer_compress = 0;
983 #endif
984 
985     if( offer_compress )
986     {
987         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
988         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
989                             MBEDTLS_SSL_COMPRESS_DEFLATE, MBEDTLS_SSL_COMPRESS_NULL ) );
990 
991         *p++ = 2;
992         *p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
993         *p++ = MBEDTLS_SSL_COMPRESS_NULL;
994     }
995     else
996     {
997         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
998         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
999                             MBEDTLS_SSL_COMPRESS_NULL ) );
1000 
1001         *p++ = 1;
1002         *p++ = MBEDTLS_SSL_COMPRESS_NULL;
1003     }
1004 
1005     // First write extensions, then the total length
1006     //
1007 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1008     ssl_write_hostname_ext( ssl, p + 2 + ext_len, &olen );
1009     ext_len += olen;
1010 #endif
1011 
1012     /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
1013      * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
1014 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1015     ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen );
1016     ext_len += olen;
1017 #endif
1018 
1019 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1020     defined(MBEDTLS_KEY_EXCHANGE__WITH_CERT__ENABLED)
1021     ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len, &olen );
1022     ext_len += olen;
1023 #endif
1024 
1025 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1026     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1027     if( uses_ec )
1028     {
1029         ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len, &olen );
1030         ext_len += olen;
1031 
1032         ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen );
1033         ext_len += olen;
1034     }
1035 #endif
1036 
1037 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1038     ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen );
1039     ext_len += olen;
1040 #endif
1041 
1042 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1043     ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen );
1044     ext_len += olen;
1045 #endif
1046 
1047 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1048     ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen );
1049     ext_len += olen;
1050 #endif
1051 
1052 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1053     ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen );
1054     ext_len += olen;
1055 #endif
1056 
1057 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1058     ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen );
1059     ext_len += olen;
1060 #endif
1061 
1062 #if defined(MBEDTLS_SSL_ALPN)
1063     ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen );
1064     ext_len += olen;
1065 #endif
1066 
1067 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1068     ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen );
1069     ext_len += olen;
1070 #endif
1071 
1072     /* olen unused if all extensions are disabled */
1073     ((void) olen);
1074 
1075     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
1076                    ext_len ) );
1077 
1078     if( ext_len > 0 )
1079     {
1080         *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
1081         *p++ = (unsigned char)( ( ext_len      ) & 0xFF );
1082         p += ext_len;
1083     }
1084 
1085     ssl->out_msglen  = p - buf;
1086     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
1087     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_HELLO;
1088 
1089     ssl->state++;
1090 
1091 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1092     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1093         mbedtls_ssl_send_flight_completed( ssl );
1094 #endif
1095 
1096     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
1097     {
1098         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
1099         return( ret );
1100     }
1101 
1102     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
1103 
1104     return( 0 );
1105 }
1106 
1107 static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
1108                                          const unsigned char *buf,
1109                                          size_t len )
1110 {
1111 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1112     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
1113     {
1114         /* Check verify-data in constant-time. The length OTOH is no secret */
1115         if( len    != 1 + ssl->verify_data_len * 2 ||
1116             buf[0] !=     ssl->verify_data_len * 2 ||
1117             mbedtls_ssl_safer_memcmp( buf + 1,
1118                           ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
1119             mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
1120                           ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
1121         {
1122             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
1123             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1124                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1125             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1126         }
1127     }
1128     else
1129 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1130     {
1131         if( len != 1 || buf[0] != 0x00 )
1132         {
1133             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) );
1134             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1135                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1136             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1137         }
1138 
1139         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
1140     }
1141 
1142     return( 0 );
1143 }
1144 
1145 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1146 static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
1147                                               const unsigned char *buf,
1148                                               size_t len )
1149 {
1150     /*
1151      * server should use the extension only if we did,
1152      * and if so the server's value should match ours (and len is always 1)
1153      */
1154     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
1155         len != 1 ||
1156         buf[0] != ssl->conf->mfl_code )
1157     {
1158         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching max fragment length extension" ) );
1159         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1160                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1161         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1162     }
1163 
1164     return( 0 );
1165 }
1166 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1167 
1168 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1169 static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
1170                                          const unsigned char *buf,
1171                                          size_t len )
1172 {
1173     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
1174         len != 0 )
1175     {
1176         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching truncated HMAC extension" ) );
1177         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1178                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1179         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1180     }
1181 
1182     ((void) buf);
1183 
1184     ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
1185 
1186     return( 0 );
1187 }
1188 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1189 
1190 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1191 static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
1192                                          const unsigned char *buf,
1193                                          size_t len )
1194 {
1195     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
1196         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
1197         len != 0 )
1198     {
1199         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching encrypt-then-MAC extension" ) );
1200         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1201                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1202         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1203     }
1204 
1205     ((void) buf);
1206 
1207     ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
1208 
1209     return( 0 );
1210 }
1211 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1212 
1213 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1214 static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
1215                                          const unsigned char *buf,
1216                                          size_t len )
1217 {
1218     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
1219         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
1220         len != 0 )
1221     {
1222         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching extended master secret extension" ) );
1223         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1224                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1225         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1226     }
1227 
1228     ((void) buf);
1229 
1230     ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
1231 
1232     return( 0 );
1233 }
1234 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1235 
1236 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1237 static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
1238                                          const unsigned char *buf,
1239                                          size_t len )
1240 {
1241     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
1242         len != 0 )
1243     {
1244         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching session ticket extension" ) );
1245         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1246                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1247         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1248     }
1249 
1250     ((void) buf);
1251 
1252     ssl->handshake->new_session_ticket = 1;
1253 
1254     return( 0 );
1255 }
1256 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1257 
1258 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1259     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1260 static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
1261                                                   const unsigned char *buf,
1262                                                   size_t len )
1263 {
1264     size_t list_size;
1265     const unsigned char *p;
1266 
1267     if( len == 0 || (size_t)( buf[0] + 1 ) != len )
1268     {
1269         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1270         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1271                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1272         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1273     }
1274     list_size = buf[0];
1275 
1276     p = buf + 1;
1277     while( list_size > 0 )
1278     {
1279         if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
1280             p[0] == MBEDTLS_ECP_PF_COMPRESSED )
1281         {
1282 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
1283             ssl->handshake->ecdh_ctx.point_format = p[0];
1284 #endif
1285 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1286             ssl->handshake->ecjpake_ctx.point_format = p[0];
1287 #endif
1288             MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
1289             return( 0 );
1290         }
1291 
1292         list_size--;
1293         p++;
1294     }
1295 
1296     MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
1297     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1298                                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1299     return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1300 }
1301 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
1302           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1303 
1304 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1305 static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
1306                                    const unsigned char *buf,
1307                                    size_t len )
1308 {
1309     int ret;
1310 
1311     if( ssl->transform_negotiate->ciphersuite_info->key_exchange !=
1312         MBEDTLS_KEY_EXCHANGE_ECJPAKE )
1313     {
1314         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
1315         return( 0 );
1316     }
1317 
1318     /* If we got here, we no longer need our cached extension */
1319     mbedtls_free( ssl->handshake->ecjpake_cache );
1320     ssl->handshake->ecjpake_cache = NULL;
1321     ssl->handshake->ecjpake_cache_len = 0;
1322 
1323     if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
1324                                                 buf, len ) ) != 0 )
1325     {
1326         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
1327         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1328                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1329         return( ret );
1330     }
1331 
1332     return( 0 );
1333 }
1334 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1335 
1336 #if defined(MBEDTLS_SSL_ALPN)
1337 static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
1338                                const unsigned char *buf, size_t len )
1339 {
1340     size_t list_len, name_len;
1341     const char **p;
1342 
1343     /* If we didn't send it, the server shouldn't send it */
1344     if( ssl->conf->alpn_list == NULL )
1345     {
1346         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
1347         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1348                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1349         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1350     }
1351 
1352     /*
1353      * opaque ProtocolName<1..2^8-1>;
1354      *
1355      * struct {
1356      *     ProtocolName protocol_name_list<2..2^16-1>
1357      * } ProtocolNameList;
1358      *
1359      * the "ProtocolNameList" MUST contain exactly one "ProtocolName"
1360      */
1361 
1362     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
1363     if( len < 4 )
1364     {
1365         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1366                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1367         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1368     }
1369 
1370     list_len = ( buf[0] << 8 ) | buf[1];
1371     if( list_len != len - 2 )
1372     {
1373         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1374                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1375         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1376     }
1377 
1378     name_len = buf[2];
1379     if( name_len != list_len - 1 )
1380     {
1381         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1382                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1383         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1384     }
1385 
1386     /* Check that the server chosen protocol was in our list and save it */
1387     for( p = ssl->conf->alpn_list; *p != NULL; p++ )
1388     {
1389         if( name_len == strlen( *p ) &&
1390             memcmp( buf + 3, *p, name_len ) == 0 )
1391         {
1392             ssl->alpn_chosen = *p;
1393             return( 0 );
1394         }
1395     }
1396 
1397     MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
1398     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1399                                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1400     return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1401 }
1402 #endif /* MBEDTLS_SSL_ALPN */
1403 
1404 /*
1405  * Parse HelloVerifyRequest.  Only called after verifying the HS type.
1406  */
1407 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1408 static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
1409 {
1410     const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
1411     int major_ver, minor_ver;
1412     unsigned char cookie_len;
1413 
1414     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
1415 
1416     /* Check that there is enough room for:
1417      * - 2 bytes of version
1418      * - 1 byte of cookie_len
1419      */
1420     if( mbedtls_ssl_hs_hdr_len( ssl ) + 3 > ssl->in_msglen )
1421     {
1422         MBEDTLS_SSL_DEBUG_MSG( 1,
1423             ( "incoming HelloVerifyRequest message is too short" ) );
1424         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1425                                     MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1426         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1427     }
1428 
1429     /*
1430      * struct {
1431      *   ProtocolVersion server_version;
1432      *   opaque cookie<0..2^8-1>;
1433      * } HelloVerifyRequest;
1434      */
1435     MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
1436     mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
1437     p += 2;
1438 
1439     /*
1440      * Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
1441      * even is lower than our min version.
1442      */
1443     if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
1444         minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
1445         major_ver > ssl->conf->max_major_ver  ||
1446         minor_ver > ssl->conf->max_minor_ver  )
1447     {
1448         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
1449 
1450         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1451                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
1452 
1453         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
1454     }
1455 
1456     cookie_len = *p++;
1457     if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
1458     {
1459         MBEDTLS_SSL_DEBUG_MSG( 1,
1460             ( "cookie length does not match incoming message size" ) );
1461         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1462                                     MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1463         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1464     }
1465     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
1466 
1467     mbedtls_free( ssl->handshake->verify_cookie );
1468 
1469     ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
1470     if( ssl->handshake->verify_cookie  == NULL )
1471     {
1472         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
1473         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
1474     }
1475 
1476     memcpy( ssl->handshake->verify_cookie, p, cookie_len );
1477     ssl->handshake->verify_cookie_len = cookie_len;
1478 
1479     /* Start over at ClientHello */
1480     ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
1481     mbedtls_ssl_reset_checksum( ssl );
1482 
1483     mbedtls_ssl_recv_flight_completed( ssl );
1484 
1485     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
1486 
1487     return( 0 );
1488 }
1489 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1490 
1491 static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
1492 {
1493     int ret, i;
1494     size_t n;
1495     size_t ext_len;
1496     unsigned char *buf, *ext;
1497     unsigned char comp;
1498 #if defined(MBEDTLS_ZLIB_SUPPORT)
1499     int accept_comp;
1500 #endif
1501 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1502     int renegotiation_info_seen = 0;
1503 #endif
1504     int handshake_failure = 0;
1505     const mbedtls_ssl_ciphersuite_t *suite_info;
1506 
1507     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
1508 
1509     buf = ssl->in_msg;
1510 
1511     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
1512     {
1513         /* No alert on a read error. */
1514         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
1515         return( ret );
1516     }
1517 
1518     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
1519     {
1520 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1521         if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
1522         {
1523             ssl->renego_records_seen++;
1524 
1525             if( ssl->conf->renego_max_records >= 0 &&
1526                 ssl->renego_records_seen > ssl->conf->renego_max_records )
1527             {
1528                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation requested, "
1529                                     "but not honored by server" ) );
1530                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
1531             }
1532 
1533             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-handshake message during renego" ) );
1534 
1535             ssl->keep_current_message = 1;
1536             return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
1537         }
1538 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1539 
1540         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1541         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1542                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
1543         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
1544     }
1545 
1546 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1547     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1548     {
1549         if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
1550         {
1551             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
1552             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
1553             return( ssl_parse_hello_verify_request( ssl ) );
1554         }
1555         else
1556         {
1557             /* We made it through the verification process */
1558             mbedtls_free( ssl->handshake->verify_cookie );
1559             ssl->handshake->verify_cookie = NULL;
1560             ssl->handshake->verify_cookie_len = 0;
1561         }
1562     }
1563 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1564 
1565     if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
1566         buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
1567     {
1568         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1569         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1570                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1571         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1572     }
1573 
1574     /*
1575      *  0   .  1    server_version
1576      *  2   . 33    random (maybe including 4 bytes of Unix time)
1577      * 34   . 34    session_id length = n
1578      * 35   . 34+n  session_id
1579      * 35+n . 36+n  cipher_suite
1580      * 37+n . 37+n  compression_method
1581      *
1582      * 38+n . 39+n  extensions length (optional)
1583      * 40+n .  ..   extensions
1584      */
1585     buf += mbedtls_ssl_hs_hdr_len( ssl );
1586 
1587     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
1588     mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
1589                       ssl->conf->transport, buf + 0 );
1590 
1591     if( ssl->major_ver < ssl->conf->min_major_ver ||
1592         ssl->minor_ver < ssl->conf->min_minor_ver ||
1593         ssl->major_ver > ssl->conf->max_major_ver ||
1594         ssl->minor_ver > ssl->conf->max_minor_ver )
1595     {
1596         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server version out of bounds - "
1597                             " min: [%d:%d], server: [%d:%d], max: [%d:%d]",
1598                             ssl->conf->min_major_ver, ssl->conf->min_minor_ver,
1599                             ssl->major_ver, ssl->minor_ver,
1600                             ssl->conf->max_major_ver, ssl->conf->max_minor_ver ) );
1601 
1602         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1603                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
1604 
1605         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
1606     }
1607 
1608     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
1609                            ( (uint32_t) buf[2] << 24 ) |
1610                            ( (uint32_t) buf[3] << 16 ) |
1611                            ( (uint32_t) buf[4] <<  8 ) |
1612                            ( (uint32_t) buf[5]       ) ) );
1613 
1614     memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
1615 
1616     n = buf[34];
1617 
1618     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, random bytes", buf + 2, 32 );
1619 
1620     if( n > 32 )
1621     {
1622         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1623         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1624                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1625         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1626     }
1627 
1628     if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
1629     {
1630         ext_len = ( ( buf[38 + n] <<  8 )
1631                   | ( buf[39 + n]       ) );
1632 
1633         if( ( ext_len > 0 && ext_len < 4 ) ||
1634             ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
1635         {
1636             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1637             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1638                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1639             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1640         }
1641     }
1642     else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
1643     {
1644         ext_len = 0;
1645     }
1646     else
1647     {
1648         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1649         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1650                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1651         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1652     }
1653 
1654     /* ciphersuite (used later) */
1655     i = ( buf[35 + n] << 8 ) | buf[36 + n];
1656 
1657     /*
1658      * Read and check compression
1659      */
1660     comp = buf[37 + n];
1661 
1662 #if defined(MBEDTLS_ZLIB_SUPPORT)
1663     /* See comments in ssl_write_client_hello() */
1664 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1665     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1666         accept_comp = 0;
1667     else
1668 #endif
1669         accept_comp = 1;
1670 
1671     if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
1672         ( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
1673 #else /* MBEDTLS_ZLIB_SUPPORT */
1674     if( comp != MBEDTLS_SSL_COMPRESS_NULL )
1675 #endif/* MBEDTLS_ZLIB_SUPPORT */
1676     {
1677         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server hello, bad compression: %d", comp ) );
1678         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1679                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1680         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
1681     }
1682 
1683     /*
1684      * Initialize update checksum functions
1685      */
1686     ssl->transform_negotiate->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
1687 
1688     if( ssl->transform_negotiate->ciphersuite_info == NULL )
1689     {
1690         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ciphersuite info for %04x not found", i ) );
1691         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1692                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
1693         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1694     }
1695 
1696     mbedtls_ssl_optimize_checksum( ssl, ssl->transform_negotiate->ciphersuite_info );
1697 
1698     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
1699     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, session id", buf + 35, n );
1700 
1701     /*
1702      * Check if the session can be resumed
1703      */
1704     if( ssl->handshake->resume == 0 || n == 0 ||
1705 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1706         ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
1707 #endif
1708         ssl->session_negotiate->ciphersuite != i ||
1709         ssl->session_negotiate->compression != comp ||
1710         ssl->session_negotiate->id_len != n ||
1711         memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
1712     {
1713         ssl->state++;
1714         ssl->handshake->resume = 0;
1715 #if defined(MBEDTLS_HAVE_TIME)
1716         ssl->session_negotiate->start = mbedtls_time( NULL );
1717 #endif
1718         ssl->session_negotiate->ciphersuite = i;
1719         ssl->session_negotiate->compression = comp;
1720         ssl->session_negotiate->id_len = n;
1721         memcpy( ssl->session_negotiate->id, buf + 35, n );
1722     }
1723     else
1724     {
1725         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
1726 
1727         if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
1728         {
1729             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
1730             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1731                                             MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
1732             return( ret );
1733         }
1734     }
1735 
1736     MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
1737                    ssl->handshake->resume ? "a" : "no" ) );
1738 
1739     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
1740     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d", buf[37 + n] ) );
1741 
1742     /*
1743      * Perform cipher suite validation in same way as in ssl_write_client_hello.
1744      */
1745     i = 0;
1746     while( 1 )
1747     {
1748         if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
1749         {
1750             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1751             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1752                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1753             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1754         }
1755 
1756         if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
1757             ssl->session_negotiate->ciphersuite )
1758         {
1759             break;
1760         }
1761     }
1762 
1763     suite_info = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite );
1764     if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver, ssl->minor_ver ) != 0 )
1765     {
1766         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1767         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1768                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1769         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1770     }
1771 
1772     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
1773 
1774     if( comp != MBEDTLS_SSL_COMPRESS_NULL
1775 #if defined(MBEDTLS_ZLIB_SUPPORT)
1776         && comp != MBEDTLS_SSL_COMPRESS_DEFLATE
1777 #endif
1778       )
1779     {
1780         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1781         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1782                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1783         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1784     }
1785     ssl->session_negotiate->compression = comp;
1786 
1787     ext = buf + 40 + n;
1788 
1789     MBEDTLS_SSL_DEBUG_MSG( 2, ( "server hello, total extension length: %d", ext_len ) );
1790 
1791     while( ext_len )
1792     {
1793         unsigned int ext_id   = ( ( ext[0] <<  8 )
1794                                 | ( ext[1]       ) );
1795         unsigned int ext_size = ( ( ext[2] <<  8 )
1796                                 | ( ext[3]       ) );
1797 
1798         if( ext_size + 4 > ext_len )
1799         {
1800             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1801             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1802                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1803             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1804         }
1805 
1806         switch( ext_id )
1807         {
1808         case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1809             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
1810 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1811             renegotiation_info_seen = 1;
1812 #endif
1813 
1814             if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
1815                                                       ext_size ) ) != 0 )
1816                 return( ret );
1817 
1818             break;
1819 
1820 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1821         case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1822             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max_fragment_length extension" ) );
1823 
1824             if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
1825                             ext + 4, ext_size ) ) != 0 )
1826             {
1827                 return( ret );
1828             }
1829 
1830             break;
1831 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1832 
1833 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1834         case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
1835             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
1836 
1837             if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
1838                             ext + 4, ext_size ) ) != 0 )
1839             {
1840                 return( ret );
1841             }
1842 
1843             break;
1844 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1845 
1846 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1847         case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
1848             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
1849 
1850             if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
1851                             ext + 4, ext_size ) ) != 0 )
1852             {
1853                 return( ret );
1854             }
1855 
1856             break;
1857 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1858 
1859 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1860         case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
1861             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended_master_secret extension" ) );
1862 
1863             if( ( ret = ssl_parse_extended_ms_ext( ssl,
1864                             ext + 4, ext_size ) ) != 0 )
1865             {
1866                 return( ret );
1867             }
1868 
1869             break;
1870 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1871 
1872 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1873         case MBEDTLS_TLS_EXT_SESSION_TICKET:
1874             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
1875 
1876             if( ( ret = ssl_parse_session_ticket_ext( ssl,
1877                             ext + 4, ext_size ) ) != 0 )
1878             {
1879                 return( ret );
1880             }
1881 
1882             break;
1883 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1884 
1885 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1886     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1887         case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1888             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported_point_formats extension" ) );
1889 
1890             if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
1891                             ext + 4, ext_size ) ) != 0 )
1892             {
1893                 return( ret );
1894             }
1895 
1896             break;
1897 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
1898           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1899 
1900 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1901         case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1902             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
1903 
1904             if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
1905                             ext + 4, ext_size ) ) != 0 )
1906             {
1907                 return( ret );
1908             }
1909 
1910             break;
1911 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1912 
1913 #if defined(MBEDTLS_SSL_ALPN)
1914         case MBEDTLS_TLS_EXT_ALPN:
1915             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
1916 
1917             if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
1918                 return( ret );
1919 
1920             break;
1921 #endif /* MBEDTLS_SSL_ALPN */
1922 
1923         default:
1924             MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)",
1925                            ext_id ) );
1926         }
1927 
1928         ext_len -= 4 + ext_size;
1929         ext += 4 + ext_size;
1930 
1931         if( ext_len > 0 && ext_len < 4 )
1932         {
1933             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1934             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1935         }
1936     }
1937 
1938     /*
1939      * Renegotiation security checks
1940      */
1941     if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1942         ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
1943     {
1944         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) );
1945         handshake_failure = 1;
1946     }
1947 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1948     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1949              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1950              renegotiation_info_seen == 0 )
1951     {
1952         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) );
1953         handshake_failure = 1;
1954     }
1955     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1956              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1957              ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
1958     {
1959         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
1960         handshake_failure = 1;
1961     }
1962     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1963              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1964              renegotiation_info_seen == 1 )
1965     {
1966         MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) );
1967         handshake_failure = 1;
1968     }
1969 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1970 
1971     if( handshake_failure == 1 )
1972     {
1973         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1974                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1975         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1976     }
1977 
1978     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
1979 
1980     return( 0 );
1981 }
1982 
1983 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
1984     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1985 static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl, unsigned char **p,
1986                                        unsigned char *end )
1987 {
1988     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1989 
1990     /*
1991      * Ephemeral DH parameters:
1992      *
1993      * struct {
1994      *     opaque dh_p<1..2^16-1>;
1995      *     opaque dh_g<1..2^16-1>;
1996      *     opaque dh_Ys<1..2^16-1>;
1997      * } ServerDHParams;
1998      */
1999     if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx, p, end ) ) != 0 )
2000     {
2001         MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
2002         return( ret );
2003     }
2004 
2005     if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
2006     {
2007         MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
2008                                     ssl->handshake->dhm_ctx.len * 8,
2009                                     ssl->conf->dhm_min_bitlen ) );
2010         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2011     }
2012 
2013     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P  );
2014     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G  );
2015     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
2016 
2017     return( ret );
2018 }
2019 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2020           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2021 
2022 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2023     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2024     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
2025     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
2026     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2027 static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
2028 {
2029     const mbedtls_ecp_curve_info *curve_info;
2030 
2031     curve_info = mbedtls_ecp_curve_info_from_grp_id( ssl->handshake->ecdh_ctx.grp.id );
2032     if( curve_info == NULL )
2033     {
2034         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2035         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2036     }
2037 
2038     MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
2039 
2040 #if defined(MBEDTLS_ECP_C)
2041     if( mbedtls_ssl_check_curve( ssl, ssl->handshake->ecdh_ctx.grp.id ) != 0 )
2042 #else
2043     if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
2044         ssl->handshake->ecdh_ctx.grp.nbits > 521 )
2045 #endif
2046         return( -1 );
2047 
2048     MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Qp", &ssl->handshake->ecdh_ctx.Qp );
2049 
2050     return( 0 );
2051 }
2052 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2053           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2054           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
2055           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2056           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2057 
2058 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2059     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2060     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
2061 static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
2062                                          unsigned char **p,
2063                                          unsigned char *end )
2064 {
2065     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2066 
2067     /*
2068      * Ephemeral ECDH parameters:
2069      *
2070      * struct {
2071      *     ECParameters curve_params;
2072      *     ECPoint      public;
2073      * } ServerECDHParams;
2074      */
2075     if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
2076                                   (const unsigned char **) p, end ) ) != 0 )
2077     {
2078         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
2079         return( ret );
2080     }
2081 
2082     if( ssl_check_server_ecdh_params( ssl ) != 0 )
2083     {
2084         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message (ECDHE curve)" ) );
2085         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2086     }
2087 
2088     return( ret );
2089 }
2090 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2091           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2092           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
2093 
2094 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
2095 static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
2096                                       unsigned char **p,
2097                                       unsigned char *end )
2098 {
2099     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2100     size_t  len;
2101     ((void) ssl);
2102 
2103     /*
2104      * PSK parameters:
2105      *
2106      * opaque psk_identity_hint<0..2^16-1>;
2107      */
2108     if( end - (*p) < 2 )
2109     {
2110         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
2111                                     "(psk_identity_hint length)" ) );
2112         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2113     }
2114     len = (*p)[0] << 8 | (*p)[1];
2115     *p += 2;
2116 
2117     if( end - (*p) < (int) len )
2118     {
2119         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message "
2120                                     "(psk_identity_hint length)" ) );
2121         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2122     }
2123 
2124     /*
2125      * Note: we currently ignore the PKS identity hint, as we only allow one
2126      * PSK to be provisionned on the client. This could be changed later if
2127      * someone needs that feature.
2128      */
2129     *p += len;
2130     ret = 0;
2131 
2132     return( ret );
2133 }
2134 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
2135 
2136 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
2137     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2138 /*
2139  * Generate a pre-master secret and encrypt it with the server's RSA key
2140  */
2141 static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
2142                                     size_t offset, size_t *olen,
2143                                     size_t pms_offset )
2144 {
2145     int ret;
2146     size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
2147     unsigned char *p = ssl->handshake->premaster + pms_offset;
2148 
2149     if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
2150     {
2151         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
2152         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2153     }
2154 
2155     /*
2156      * Generate (part of) the pre-master as
2157      *  struct {
2158      *      ProtocolVersion client_version;
2159      *      opaque random[46];
2160      *  } PreMasterSecret;
2161      */
2162     mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
2163                        ssl->conf->transport, p );
2164 
2165     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
2166     {
2167         MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
2168         return( ret );
2169     }
2170 
2171     ssl->handshake->pmslen = 48;
2172 
2173     if( ssl->session_negotiate->peer_cert == NULL )
2174     {
2175         MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
2176         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2177     }
2178 
2179     /*
2180      * Now write it out, encrypted
2181      */
2182     if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
2183                 MBEDTLS_PK_RSA ) )
2184     {
2185         MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
2186         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2187     }
2188 
2189     if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
2190                             p, ssl->handshake->pmslen,
2191                             ssl->out_msg + offset + len_bytes, olen,
2192                             MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
2193                             ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2194     {
2195         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
2196         return( ret );
2197     }
2198 
2199 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2200     defined(MBEDTLS_SSL_PROTO_TLS1_2)
2201     if( len_bytes == 2 )
2202     {
2203         ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
2204         ssl->out_msg[offset+1] = (unsigned char)( *olen      );
2205         *olen += 2;
2206     }
2207 #endif
2208 
2209     return( 0 );
2210 }
2211 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
2212           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2213 
2214 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2215 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2216     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2217     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
2218 static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
2219                                           unsigned char **p,
2220                                           unsigned char *end,
2221                                           mbedtls_md_type_t *md_alg,
2222                                           mbedtls_pk_type_t *pk_alg )
2223 {
2224     ((void) ssl);
2225     *md_alg = MBEDTLS_MD_NONE;
2226     *pk_alg = MBEDTLS_PK_NONE;
2227 
2228     /* Only in TLS 1.2 */
2229     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
2230     {
2231         return( 0 );
2232     }
2233 
2234     if( (*p) + 2 > end )
2235         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2236 
2237     /*
2238      * Get hash algorithm
2239      */
2240     if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
2241     {
2242         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
2243                             "HashAlgorithm %d", *(p)[0] ) );
2244         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2245     }
2246 
2247     /*
2248      * Get signature algorithm
2249      */
2250     if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
2251     {
2252         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
2253                             "SignatureAlgorithm %d", (*p)[1] ) );
2254         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2255     }
2256 
2257     /*
2258      * Check if the hash is acceptable
2259      */
2260     if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
2261     {
2262         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm %d that was not offered",
2263                                     *(p)[0] ) );
2264         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2265     }
2266 
2267     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
2268     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
2269     *p += 2;
2270 
2271     return( 0 );
2272 }
2273 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2274           MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2275           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2276 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2277 
2278 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2279     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2280 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
2281 {
2282     int ret;
2283     const mbedtls_ecp_keypair *peer_key;
2284 
2285     if( ssl->session_negotiate->peer_cert == NULL )
2286     {
2287         MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
2288         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2289     }
2290 
2291     if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
2292                      MBEDTLS_PK_ECKEY ) )
2293     {
2294         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
2295         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2296     }
2297 
2298     peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
2299 
2300     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
2301                                  MBEDTLS_ECDH_THEIRS ) ) != 0 )
2302     {
2303         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
2304         return( ret );
2305     }
2306 
2307     if( ssl_check_server_ecdh_params( ssl ) != 0 )
2308     {
2309         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
2310         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2311     }
2312 
2313     return( ret );
2314 }
2315 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
2316           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2317 
2318 static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
2319 {
2320     int ret;
2321     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2322         ssl->transform_negotiate->ciphersuite_info;
2323     unsigned char *p = NULL, *end = NULL;
2324 
2325     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
2326 
2327 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
2328     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
2329     {
2330         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
2331         ssl->state++;
2332         return( 0 );
2333     }
2334     ((void) p);
2335     ((void) end);
2336 #endif
2337 
2338 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2339     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2340     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2341         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
2342     {
2343         if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
2344         {
2345             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
2346             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2347                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2348             return( ret );
2349         }
2350 
2351         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
2352         ssl->state++;
2353         return( 0 );
2354     }
2355     ((void) p);
2356     ((void) end);
2357 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2358           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2359 
2360     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
2361     {
2362         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2363         return( ret );
2364     }
2365 
2366     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2367     {
2368         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2369         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2370                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2371         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2372     }
2373 
2374     /*
2375      * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
2376      * doesn't use a psk_identity_hint
2377      */
2378     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
2379     {
2380         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2381             ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2382         {
2383             /* Current message is probably either
2384              * CertificateRequest or ServerHelloDone */
2385             ssl->keep_current_message = 1;
2386             goto exit;
2387         }
2388 
2389         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key exchange message must "
2390                                     "not be skipped" ) );
2391         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2392                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2393 
2394         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2395     }
2396 
2397     p   = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
2398     end = ssl->in_msg + ssl->in_hslen;
2399     MBEDTLS_SSL_DEBUG_BUF( 3,   "server key exchange", p, end - p );
2400 
2401 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
2402     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2403         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
2404         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2405         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
2406     {
2407         if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
2408         {
2409             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2410             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2411                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2412             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2413         }
2414     } /* FALLTROUGH */
2415 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
2416 
2417 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) ||                       \
2418     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2419     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2420         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2421         ; /* nothing more to do */
2422     else
2423 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
2424           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2425 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2426     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
2427     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
2428         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
2429     {
2430         if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
2431         {
2432             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2433             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2434                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2435             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2436         }
2437     }
2438     else
2439 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2440           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2441 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2442     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
2443     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
2444     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2445         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
2446         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
2447     {
2448         if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
2449         {
2450             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2451             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2452                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2453             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2454         }
2455     }
2456     else
2457 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2458           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
2459           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2460 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2461     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
2462     {
2463         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
2464                                               p, end - p );
2465         if( ret != 0 )
2466         {
2467             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
2468             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2469                                             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2470             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2471         }
2472     }
2473     else
2474 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2475     {
2476         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2477         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2478     }
2479 
2480 #if defined(MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED)
2481     if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
2482     {
2483         size_t sig_len, hashlen;
2484         unsigned char hash[64];
2485         mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
2486         mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
2487         unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
2488         size_t params_len = p - params;
2489 
2490         /*
2491          * Handle the digitally-signed structure
2492          */
2493 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2494         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
2495         {
2496             if( ssl_parse_signature_algorithm( ssl, &p, end,
2497                                                &md_alg, &pk_alg ) != 0 )
2498             {
2499                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2500                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2501                                                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2502                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2503             }
2504 
2505             if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
2506             {
2507                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2508                 mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2509                                                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2510                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2511             }
2512         }
2513         else
2514 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2515 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2516     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2517         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
2518         {
2519             pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
2520 
2521             /* Default hash for ECDSA is SHA-1 */
2522             if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
2523                 md_alg = MBEDTLS_MD_SHA1;
2524         }
2525         else
2526 #endif
2527         {
2528             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2529             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2530         }
2531 
2532         /*
2533          * Read signature
2534          */
2535         if( p > end - 2 )
2536         {
2537             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2538             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2539                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2540             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2541         }
2542         sig_len = ( p[0] << 8 ) | p[1];
2543         p += 2;
2544 
2545         if( p != end - sig_len )
2546         {
2547             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2548             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2549                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2550             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2551         }
2552 
2553         MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
2554 
2555         /*
2556          * Compute the hash that has been signed
2557          */
2558 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2559     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2560         if( md_alg == MBEDTLS_MD_NONE )
2561         {
2562             hashlen = 36;
2563             ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
2564                                                            params_len );
2565             if( ret != 0 )
2566                 return( ret );
2567         }
2568         else
2569 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
2570           MBEDTLS_SSL_PROTO_TLS1_1 */
2571 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2572     defined(MBEDTLS_SSL_PROTO_TLS1_2)
2573         if( md_alg != MBEDTLS_MD_NONE )
2574         {
2575             /* Info from md_alg will be used instead */
2576             hashlen = 0;
2577             ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, params,
2578                                                           params_len, md_alg );
2579             if( ret != 0 )
2580                 return( ret );
2581         }
2582         else
2583 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2584           MBEDTLS_SSL_PROTO_TLS1_2 */
2585         {
2586             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2587             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2588         }
2589 
2590         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
2591             (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
2592 
2593         if( ssl->session_negotiate->peer_cert == NULL )
2594         {
2595             MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
2596             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2597                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2598             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2599         }
2600 
2601         /*
2602          * Verify signature
2603          */
2604         if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
2605         {
2606             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2607             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2608                                             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2609             return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2610         }
2611 
2612         if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
2613                                md_alg, hash, hashlen, p, sig_len ) ) != 0 )
2614         {
2615             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2616                                             MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
2617             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
2618             return( ret );
2619         }
2620     }
2621 #endif /* MBEDTLS_KEY_EXCHANGE__WITH_SERVER_SIGNATURE__ENABLED */
2622 
2623 exit:
2624     ssl->state++;
2625 
2626     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
2627 
2628     return( 0 );
2629 }
2630 
2631 #if ! defined(MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED)
2632 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
2633 {
2634     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2635         ssl->transform_negotiate->ciphersuite_info;
2636 
2637     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
2638 
2639     if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
2640     {
2641         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
2642         ssl->state++;
2643         return( 0 );
2644     }
2645 
2646     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2647     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2648 }
2649 #else /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
2650 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
2651 {
2652     int ret;
2653     unsigned char *buf;
2654     size_t n = 0;
2655     size_t cert_type_len = 0, dn_len = 0;
2656     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2657         ssl->transform_negotiate->ciphersuite_info;
2658 
2659     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
2660 
2661     if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
2662     {
2663         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
2664         ssl->state++;
2665         return( 0 );
2666     }
2667 
2668     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
2669     {
2670         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2671         return( ret );
2672     }
2673 
2674     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2675     {
2676         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2677         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2678                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2679         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2680     }
2681 
2682     ssl->state++;
2683     ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
2684 
2685     MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
2686                         ssl->client_auth ? "a" : "no" ) );
2687 
2688     if( ssl->client_auth == 0 )
2689     {
2690         /* Current message is probably the ServerHelloDone */
2691         ssl->keep_current_message = 1;
2692         goto exit;
2693     }
2694 
2695     /*
2696      *  struct {
2697      *      ClientCertificateType certificate_types<1..2^8-1>;
2698      *      SignatureAndHashAlgorithm
2699      *        supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
2700      *      DistinguishedName certificate_authorities<0..2^16-1>;
2701      *  } CertificateRequest;
2702      *
2703      *  Since we only support a single certificate on clients, let's just
2704      *  ignore all the information that's supposed to help us pick a
2705      *  certificate.
2706      *
2707      *  We could check that our certificate matches the request, and bail out
2708      *  if it doesn't, but it's simpler to just send the certificate anyway,
2709      *  and give the server the opportunity to decide if it should terminate
2710      *  the connection when it doesn't like our certificate.
2711      *
2712      *  Same goes for the hash in TLS 1.2's signature_algorithms: at this
2713      *  point we only have one hash available (see comments in
2714      *  write_certificate_verify), so let's just use what we have.
2715      *
2716      *  However, we still minimally parse the message to check it is at least
2717      *  superficially sane.
2718      */
2719     buf = ssl->in_msg;
2720 
2721     /* certificate_types */
2722     if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) )
2723     {
2724         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2725         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2726                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2727         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
2728     }
2729     cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
2730     n = cert_type_len;
2731 
2732     /*
2733      * In the subsequent code there are two paths that read from buf:
2734      *     * the length of the signature algorithms field (if minor version of
2735      *       SSL is 3),
2736      *     * distinguished name length otherwise.
2737      * Both reach at most the index:
2738      *    ...hdr_len + 2 + n,
2739      * therefore the buffer length at this point must be greater than that
2740      * regardless of the actual code path.
2741      */
2742     if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
2743     {
2744         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2745         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2746                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2747         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
2748     }
2749 
2750     /* supported_signature_algorithms */
2751 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2752     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
2753     {
2754         size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
2755                              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
2756 #if defined(MBEDTLS_DEBUG_C)
2757         unsigned char* sig_alg;
2758         size_t i;
2759 #endif
2760 
2761         /*
2762          * The furthest access in buf is in the loop few lines below:
2763          *     sig_alg[i + 1],
2764          * where:
2765          *     sig_alg = buf + ...hdr_len + 3 + n,
2766          *     max(i) = sig_alg_len - 1.
2767          * Therefore the furthest access is:
2768          *     buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1],
2769          * which reduces to:
2770          *     buf[...hdr_len + 3 + n + sig_alg_len],
2771          * which is one less than we need the buf to be.
2772          */
2773         if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n + sig_alg_len )
2774         {
2775             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2776             mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2777                                             MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2778             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
2779         }
2780 
2781 #if defined(MBEDTLS_DEBUG_C)
2782         sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
2783         for( i = 0; i < sig_alg_len; i += 2 )
2784         {
2785             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d"
2786                                         ",%d", sig_alg[i], sig_alg[i + 1]  ) );
2787         }
2788 #endif
2789 
2790         n += 2 + sig_alg_len;
2791     }
2792 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2793 
2794     /* certificate_authorities */
2795     dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
2796              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
2797 
2798     n += dn_len;
2799     if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
2800     {
2801         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2802         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2803                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2804         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
2805     }
2806 
2807 exit:
2808     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
2809 
2810     return( 0 );
2811 }
2812 #endif /* MBEDTLS_KEY_EXCHANGE__CERT_REQ_ALLOWED__ENABLED */
2813 
2814 static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
2815 {
2816     int ret;
2817 
2818     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
2819 
2820     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
2821     {
2822         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2823         return( ret );
2824     }
2825 
2826     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2827     {
2828         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
2829         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2830     }
2831 
2832     if( ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ||
2833         ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
2834     {
2835         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
2836         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2837                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2838         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
2839     }
2840 
2841     ssl->state++;
2842 
2843 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2844     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2845         mbedtls_ssl_recv_flight_completed( ssl );
2846 #endif
2847 
2848     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
2849 
2850     return( 0 );
2851 }
2852 
2853 static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
2854 {
2855     int ret;
2856     size_t i, n;
2857     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2858         ssl->transform_negotiate->ciphersuite_info;
2859 
2860     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
2861 
2862 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
2863     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
2864     {
2865         /*
2866          * DHM key exchange -- send G^X mod P
2867          */
2868         n = ssl->handshake->dhm_ctx.len;
2869 
2870         ssl->out_msg[4] = (unsigned char)( n >> 8 );
2871         ssl->out_msg[5] = (unsigned char)( n      );
2872         i = 6;
2873 
2874         ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
2875                                 (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
2876                                &ssl->out_msg[i], n,
2877                                 ssl->conf->f_rng, ssl->conf->p_rng );
2878         if( ret != 0 )
2879         {
2880             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
2881             return( ret );
2882         }
2883 
2884         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
2885         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
2886 
2887         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
2888                                       ssl->handshake->premaster,
2889                                       MBEDTLS_PREMASTER_SIZE,
2890                                      &ssl->handshake->pmslen,
2891                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2892         {
2893             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
2894             return( ret );
2895         }
2896 
2897         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
2898     }
2899     else
2900 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
2901 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2902     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2903     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
2904     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2905     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2906         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
2907         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2908         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
2909     {
2910         /*
2911          * ECDH key exchange -- send client public value
2912          */
2913         i = 4;
2914 
2915         ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
2916                                 &n,
2917                                 &ssl->out_msg[i], 1000,
2918                                 ssl->conf->f_rng, ssl->conf->p_rng );
2919         if( ret != 0 )
2920         {
2921             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
2922             return( ret );
2923         }
2924 
2925         MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
2926 
2927         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
2928                                       &ssl->handshake->pmslen,
2929                                        ssl->handshake->premaster,
2930                                        MBEDTLS_MPI_MAX_SIZE,
2931                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2932         {
2933             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
2934             return( ret );
2935         }
2936 
2937         MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
2938     }
2939     else
2940 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2941           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2942           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2943           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2944 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
2945     if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
2946     {
2947         /*
2948          * opaque psk_identity<0..2^16-1>;
2949          */
2950         if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
2951         {
2952             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
2953             return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
2954         }
2955 
2956         i = 4;
2957         n = ssl->conf->psk_identity_len;
2958 
2959         if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
2960         {
2961             MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
2962                                         "SSL buffer too short" ) );
2963             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2964         }
2965 
2966         ssl->out_msg[i++] = (unsigned char)( n >> 8 );
2967         ssl->out_msg[i++] = (unsigned char)( n      );
2968 
2969         memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
2970         i += ssl->conf->psk_identity_len;
2971 
2972 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
2973         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
2974         {
2975             n = 0;
2976         }
2977         else
2978 #endif
2979 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2980         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2981         {
2982             if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
2983                 return( ret );
2984         }
2985         else
2986 #endif
2987 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
2988         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
2989         {
2990             /*
2991              * ClientDiffieHellmanPublic public (DHM send G^X mod P)
2992              */
2993             n = ssl->handshake->dhm_ctx.len;
2994 
2995             if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
2996             {
2997                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
2998                                             " or SSL buffer too short" ) );
2999                 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3000             }
3001 
3002             ssl->out_msg[i++] = (unsigned char)( n >> 8 );
3003             ssl->out_msg[i++] = (unsigned char)( n      );
3004 
3005             ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
3006                     (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
3007                     &ssl->out_msg[i], n,
3008                     ssl->conf->f_rng, ssl->conf->p_rng );
3009             if( ret != 0 )
3010             {
3011                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
3012                 return( ret );
3013             }
3014         }
3015         else
3016 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3017 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3018         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
3019         {
3020             /*
3021              * ClientECDiffieHellmanPublic public;
3022              */
3023             ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
3024                     &ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
3025                     ssl->conf->f_rng, ssl->conf->p_rng );
3026             if( ret != 0 )
3027             {
3028                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
3029                 return( ret );
3030             }
3031 
3032             MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
3033         }
3034         else
3035 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
3036         {
3037             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3038             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3039         }
3040 
3041         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
3042                         ciphersuite_info->key_exchange ) ) != 0 )
3043         {
3044             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
3045             return( ret );
3046         }
3047     }
3048     else
3049 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
3050 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
3051     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
3052     {
3053         i = 4;
3054         if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
3055             return( ret );
3056     }
3057     else
3058 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
3059 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3060     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
3061     {
3062         i = 4;
3063 
3064         ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
3065                 ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
3066                 ssl->conf->f_rng, ssl->conf->p_rng );
3067         if( ret != 0 )
3068         {
3069             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
3070             return( ret );
3071         }
3072 
3073         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
3074                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
3075                 ssl->conf->f_rng, ssl->conf->p_rng );
3076         if( ret != 0 )
3077         {
3078             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
3079             return( ret );
3080         }
3081     }
3082     else
3083 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
3084     {
3085         ((void) ciphersuite_info);
3086         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3087         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3088     }
3089 
3090     ssl->out_msglen  = i + n;
3091     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3092     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
3093 
3094     ssl->state++;
3095 
3096     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
3097     {
3098         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
3099         return( ret );
3100     }
3101 
3102     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
3103 
3104     return( 0 );
3105 }
3106 
3107 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
3108     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
3109     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \
3110     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
3111     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
3112     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
3113 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
3114 {
3115     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3116         ssl->transform_negotiate->ciphersuite_info;
3117     int ret;
3118 
3119     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
3120 
3121     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
3122     {
3123         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
3124         return( ret );
3125     }
3126 
3127     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
3128         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3129         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
3130         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
3131         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
3132     {
3133         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3134         ssl->state++;
3135         return( 0 );
3136     }
3137 
3138     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3139     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3140 }
3141 #else
3142 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
3143 {
3144     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3145     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3146         ssl->transform_negotiate->ciphersuite_info;
3147     size_t n = 0, offset = 0;
3148     unsigned char hash[48];
3149     unsigned char *hash_start = hash;
3150     mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
3151     unsigned int hashlen;
3152 
3153     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
3154 
3155     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
3156     {
3157         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
3158         return( ret );
3159     }
3160 
3161     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
3162         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3163         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
3164         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
3165         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
3166     {
3167         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3168         ssl->state++;
3169         return( 0 );
3170     }
3171 
3172     if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
3173     {
3174         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3175         ssl->state++;
3176         return( 0 );
3177     }
3178 
3179     if( mbedtls_ssl_own_key( ssl ) == NULL )
3180     {
3181         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
3182         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
3183     }
3184 
3185     /*
3186      * Make an RSA signature of the handshake digests
3187      */
3188     ssl->handshake->calc_verify( ssl, hash );
3189 
3190 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3191     defined(MBEDTLS_SSL_PROTO_TLS1_1)
3192     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
3193     {
3194         /*
3195          * digitally-signed struct {
3196          *     opaque md5_hash[16];
3197          *     opaque sha_hash[20];
3198          * };
3199          *
3200          * md5_hash
3201          *     MD5(handshake_messages);
3202          *
3203          * sha_hash
3204          *     SHA(handshake_messages);
3205          */
3206         hashlen = 36;
3207         md_alg = MBEDTLS_MD_NONE;
3208 
3209         /*
3210          * For ECDSA, default hash is SHA-1 only
3211          */
3212         if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
3213         {
3214             hash_start += 16;
3215             hashlen -= 16;
3216             md_alg = MBEDTLS_MD_SHA1;
3217         }
3218     }
3219     else
3220 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
3221           MBEDTLS_SSL_PROTO_TLS1_1 */
3222 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3223     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
3224     {
3225         /*
3226          * digitally-signed struct {
3227          *     opaque handshake_messages[handshake_messages_length];
3228          * };
3229          *
3230          * Taking shortcut here. We assume that the server always allows the
3231          * PRF Hash function and has sent it in the allowed signature
3232          * algorithms list received in the Certificate Request message.
3233          *
3234          * Until we encounter a server that does not, we will take this
3235          * shortcut.
3236          *
3237          * Reason: Otherwise we should have running hashes for SHA512 and SHA224
3238          *         in order to satisfy 'weird' needs from the server side.
3239          */
3240         if( ssl->transform_negotiate->ciphersuite_info->mac ==
3241             MBEDTLS_MD_SHA384 )
3242         {
3243             md_alg = MBEDTLS_MD_SHA384;
3244             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
3245         }
3246         else
3247         {
3248             md_alg = MBEDTLS_MD_SHA256;
3249             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
3250         }
3251         ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
3252 
3253         /* Info from md_alg will be used instead */
3254         hashlen = 0;
3255         offset = 2;
3256     }
3257     else
3258 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3259     {
3260         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3261         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3262     }
3263 
3264     if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
3265                          ssl->out_msg + 6 + offset, &n,
3266                          ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3267     {
3268         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
3269         return( ret );
3270     }
3271 
3272     ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
3273     ssl->out_msg[5 + offset] = (unsigned char)( n      );
3274 
3275     ssl->out_msglen  = 6 + n + offset;
3276     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3277     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
3278 
3279     ssl->state++;
3280 
3281     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
3282     {
3283         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
3284         return( ret );
3285     }
3286 
3287     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
3288 
3289     return( ret );
3290 }
3291 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
3292           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
3293           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
3294           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
3295           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
3296           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
3297 
3298 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3299 static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
3300 {
3301     int ret;
3302     uint32_t lifetime;
3303     size_t ticket_len;
3304     unsigned char *ticket;
3305     const unsigned char *msg;
3306 
3307     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
3308 
3309     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
3310     {
3311         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
3312         return( ret );
3313     }
3314 
3315     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
3316     {
3317         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3318         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3319                                         MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
3320         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3321     }
3322 
3323     /*
3324      * struct {
3325      *     uint32 ticket_lifetime_hint;
3326      *     opaque ticket<0..2^16-1>;
3327      * } NewSessionTicket;
3328      *
3329      * 0  .  3   ticket_lifetime_hint
3330      * 4  .  5   ticket_len (n)
3331      * 6  .  5+n ticket content
3332      */
3333     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
3334         ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
3335     {
3336         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3337         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3338                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3339         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
3340     }
3341 
3342     msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
3343 
3344     lifetime = ( ((uint32_t) msg[0]) << 24 ) | ( msg[1] << 16 ) |
3345                ( msg[2] << 8 ) | ( msg[3] );
3346 
3347     ticket_len = ( msg[4] << 8 ) | ( msg[5] );
3348 
3349     if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
3350     {
3351         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3352         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3353                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3354         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
3355     }
3356 
3357     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
3358 
3359     /* We're not waiting for a NewSessionTicket message any more */
3360     ssl->handshake->new_session_ticket = 0;
3361     ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
3362 
3363     /*
3364      * Zero-length ticket means the server changed his mind and doesn't want
3365      * to send a ticket after all, so just forget it
3366      */
3367     if( ticket_len == 0 )
3368         return( 0 );
3369 
3370     mbedtls_zeroize( ssl->session_negotiate->ticket,
3371                       ssl->session_negotiate->ticket_len );
3372     mbedtls_free( ssl->session_negotiate->ticket );
3373     ssl->session_negotiate->ticket = NULL;
3374     ssl->session_negotiate->ticket_len = 0;
3375 
3376     if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
3377     {
3378         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
3379         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3380                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
3381         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
3382     }
3383 
3384     memcpy( ticket, msg + 6, ticket_len );
3385 
3386     ssl->session_negotiate->ticket = ticket;
3387     ssl->session_negotiate->ticket_len = ticket_len;
3388     ssl->session_negotiate->ticket_lifetime = lifetime;
3389 
3390     /*
3391      * RFC 5077 section 3.4:
3392      * "If the client receives a session ticket from the server, then it
3393      * discards any Session ID that was sent in the ServerHello."
3394      */
3395     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
3396     ssl->session_negotiate->id_len = 0;
3397 
3398     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
3399 
3400     return( 0 );
3401 }
3402 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3403 
3404 /*
3405  * SSL handshake -- client side -- single step
3406  */
3407 int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
3408 {
3409     int ret = 0;
3410 
3411     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
3412         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3413 
3414     MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
3415 
3416     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
3417         return( ret );
3418 
3419 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3420     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3421         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
3422     {
3423         if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
3424             return( ret );
3425     }
3426 #endif
3427 
3428     /* Change state now, so that it is right in mbedtls_ssl_read_record(), used
3429      * by DTLS for dropping out-of-sequence ChangeCipherSpec records */
3430 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3431     if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
3432         ssl->handshake->new_session_ticket != 0 )
3433     {
3434         ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
3435     }
3436 #endif
3437 
3438     switch( ssl->state )
3439     {
3440         case MBEDTLS_SSL_HELLO_REQUEST:
3441             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
3442             break;
3443 
3444        /*
3445         *  ==>   ClientHello
3446         */
3447        case MBEDTLS_SSL_CLIENT_HELLO:
3448            ret = ssl_write_client_hello( ssl );
3449            break;
3450 
3451        /*
3452         *  <==   ServerHello
3453         *        Certificate
3454         *      ( ServerKeyExchange  )
3455         *      ( CertificateRequest )
3456         *        ServerHelloDone
3457         */
3458        case MBEDTLS_SSL_SERVER_HELLO:
3459            ret = ssl_parse_server_hello( ssl );
3460            break;
3461 
3462        case MBEDTLS_SSL_SERVER_CERTIFICATE:
3463            ret = mbedtls_ssl_parse_certificate( ssl );
3464            break;
3465 
3466        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
3467            ret = ssl_parse_server_key_exchange( ssl );
3468            break;
3469 
3470        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
3471            ret = ssl_parse_certificate_request( ssl );
3472            break;
3473 
3474        case MBEDTLS_SSL_SERVER_HELLO_DONE:
3475            ret = ssl_parse_server_hello_done( ssl );
3476            break;
3477 
3478        /*
3479         *  ==> ( Certificate/Alert  )
3480         *        ClientKeyExchange
3481         *      ( CertificateVerify  )
3482         *        ChangeCipherSpec
3483         *        Finished
3484         */
3485        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
3486            ret = mbedtls_ssl_write_certificate( ssl );
3487            break;
3488 
3489        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
3490            ret = ssl_write_client_key_exchange( ssl );
3491            break;
3492 
3493        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
3494            ret = ssl_write_certificate_verify( ssl );
3495            break;
3496 
3497        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
3498            ret = mbedtls_ssl_write_change_cipher_spec( ssl );
3499            break;
3500 
3501        case MBEDTLS_SSL_CLIENT_FINISHED:
3502            ret = mbedtls_ssl_write_finished( ssl );
3503            break;
3504 
3505        /*
3506         *  <==   ( NewSessionTicket )
3507         *        ChangeCipherSpec
3508         *        Finished
3509         */
3510 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3511        case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
3512            ret = ssl_parse_new_session_ticket( ssl );
3513            break;
3514 #endif
3515 
3516        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
3517            ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
3518            break;
3519 
3520        case MBEDTLS_SSL_SERVER_FINISHED:
3521            ret = mbedtls_ssl_parse_finished( ssl );
3522            break;
3523 
3524        case MBEDTLS_SSL_FLUSH_BUFFERS:
3525            MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
3526            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3527            break;
3528 
3529        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
3530            mbedtls_ssl_handshake_wrapup( ssl );
3531            break;
3532 
3533        default:
3534            MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
3535            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3536    }
3537 
3538     return( ret );
3539 }
3540 #endif /* MBEDTLS_SSL_CLI_C */
3541