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