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