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