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