replace : iotivity -> iotivity-sec
[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 < 1 || n > 65535 || *p + n > end )
2008     {
2009         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2010         return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE );
2011     }
2012
2013     if( ssl->conf->f_psk != NULL )
2014     {
2015         if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 )
2016             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
2017     }
2018     else
2019     {
2020         /* Identity is not a big secret since clients send it in the clear,
2021          * but treat it carefully anyway, just in case */
2022         if( n != ssl->conf->psk_identity_len ||
2023             mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 )
2024         {
2025             ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
2026         }
2027     }
2028
2029     if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY )
2030     {
2031         MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n );
2032         if( ( ret = mbedtls_ssl_send_alert_message( ssl,
2033                               MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2034                               MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ) ) != 0 )
2035         {
2036             return( ret );
2037         }
2038
2039         return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY );
2040     }
2041
2042     *p += n;
2043
2044     return( 0 );
2045 }
2046 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
2047
2048 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
2049     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2050 /*
2051  * Generate a pre-master secret and encrypt it with the server's RSA key
2052  */
2053 static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
2054                                     size_t offset, size_t *olen,
2055                                     size_t pms_offset )
2056 {
2057     int ret;
2058     size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
2059     unsigned char *p = ssl->handshake->premaster + pms_offset;
2060
2061     if( offset + len_bytes > MBEDTLS_SSL_MAX_CONTENT_LEN )
2062     {
2063         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
2064         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2065     }
2066
2067     /*
2068      * Generate (part of) the pre-master as
2069      *  struct {
2070      *      ProtocolVersion client_version;
2071      *      opaque random[46];
2072      *  } PreMasterSecret;
2073      */
2074     mbedtls_ssl_write_version( ssl->conf->max_major_ver, ssl->conf->max_minor_ver,
2075                        ssl->conf->transport, p );
2076
2077     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
2078     {
2079         MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
2080         return( ret );
2081     }
2082
2083     ssl->handshake->pmslen = 48;
2084
2085     if( ssl->session_negotiate->peer_cert == NULL )
2086     {
2087         MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
2088         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2089     }
2090
2091     /*
2092      * Now write it out, encrypted
2093      */
2094     if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
2095                 MBEDTLS_PK_RSA ) )
2096     {
2097         MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
2098         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2099     }
2100
2101     if( ( ret = mbedtls_pk_encrypt( &ssl->session_negotiate->peer_cert->pk,
2102                             p, ssl->handshake->pmslen,
2103                             ssl->out_msg + offset + len_bytes, olen,
2104                             MBEDTLS_SSL_MAX_CONTENT_LEN - offset - len_bytes,
2105                             ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2106     {
2107         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
2108         return( ret );
2109     }
2110
2111 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2112     defined(MBEDTLS_SSL_PROTO_TLS1_2)
2113     if( len_bytes == 2 )
2114     {
2115         ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
2116         ssl->out_msg[offset+1] = (unsigned char)( *olen      );
2117         *olen += 2;
2118     }
2119 #endif
2120
2121     return( 0 );
2122 }
2123 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
2124           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2125
2126 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2127 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2128     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2129     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
2130 static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
2131                                           unsigned char **p,
2132                                           unsigned char *end,
2133                                           mbedtls_md_type_t *md_alg,
2134                                           mbedtls_pk_type_t *pk_alg )
2135 {
2136     ((void) ssl);
2137     *md_alg = MBEDTLS_MD_NONE;
2138     *pk_alg = MBEDTLS_PK_NONE;
2139
2140     /* Only in TLS 1.2 */
2141     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
2142     {
2143         return( 0 );
2144     }
2145
2146     if( (*p) + 2 > end )
2147         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2148
2149     /*
2150      * Get hash algorithm
2151      */
2152     if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) ) == MBEDTLS_MD_NONE )
2153     {
2154         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Server used unsupported "
2155                             "HashAlgorithm %d", *(p)[0] ) );
2156         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2157     }
2158
2159     /*
2160      * Get signature algorithm
2161      */
2162     if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) ) == MBEDTLS_PK_NONE )
2163     {
2164         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used unsupported "
2165                             "SignatureAlgorithm %d", (*p)[1] ) );
2166         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2167     }
2168
2169     /*
2170      * Check if the hash is acceptable
2171      */
2172     if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
2173     {
2174         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server used HashAlgorithm "
2175                                     "that was not offered" ) );
2176         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2177     }
2178
2179     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d", (*p)[1] ) );
2180     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d", (*p)[0] ) );
2181     *p += 2;
2182
2183     return( 0 );
2184 }
2185 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2186           MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2187           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2188 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2189
2190 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2191     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2192 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
2193 {
2194     int ret;
2195     const mbedtls_ecp_keypair *peer_key;
2196
2197     if( ssl->session_negotiate->peer_cert == NULL )
2198     {
2199         MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
2200         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2201     }
2202
2203     if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk,
2204                      MBEDTLS_PK_ECKEY ) )
2205     {
2206         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
2207         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2208     }
2209
2210     peer_key = mbedtls_pk_ec( ssl->session_negotiate->peer_cert->pk );
2211
2212     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
2213                                  MBEDTLS_ECDH_THEIRS ) ) != 0 )
2214     {
2215         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
2216         return( ret );
2217     }
2218
2219     if( ssl_check_server_ecdh_params( ssl ) != 0 )
2220     {
2221         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
2222         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
2223     }
2224
2225     return( ret );
2226 }
2227 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
2228           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2229
2230 static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
2231 {
2232     int ret;
2233     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
2234     unsigned char *p, *end;
2235
2236     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
2237
2238 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
2239     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
2240     {
2241         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
2242         ssl->state++;
2243         return( 0 );
2244     }
2245     ((void) p);
2246     ((void) end);
2247 #endif
2248
2249 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2250     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
2251     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2252         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
2253     {
2254         if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
2255         {
2256             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
2257             return( ret );
2258         }
2259
2260         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
2261         ssl->state++;
2262         return( 0 );
2263     }
2264     ((void) p);
2265     ((void) end);
2266 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2267           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2268
2269     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
2270     {
2271         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2272         return( ret );
2273     }
2274
2275     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2276     {
2277         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2278         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2279     }
2280
2281     /*
2282      * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
2283      * doesn't use a psk_identity_hint
2284      */
2285     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
2286     {
2287         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2288             ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2289         {
2290             ssl->record_read = 1;
2291             goto exit;
2292         }
2293
2294         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2295         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2296     }
2297
2298     p   = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
2299     end = ssl->in_msg + ssl->in_hslen;
2300     MBEDTLS_SSL_DEBUG_BUF( 3,   "server key exchange", p, end - p );
2301
2302 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
2303     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2304         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
2305         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2306         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
2307     {
2308         if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
2309         {
2310             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2311             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2312         }
2313     } /* FALLTROUGH */
2314 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
2315
2316 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) ||                       \
2317     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2318     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2319         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2320         ; /* nothing more to do */
2321     else
2322 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
2323           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2324 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2325     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
2326     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
2327         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
2328     {
2329         if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
2330         {
2331             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2332             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2333         }
2334     }
2335     else
2336 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2337           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2338 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2339     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
2340     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2341     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ANON_ENABLED)
2342     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2343         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
2344         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
2345         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
2346     {
2347         if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
2348         {
2349             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2350             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2351         }
2352     }
2353     else
2354 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2355           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
2356           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2357           MBEDTLS_KEY_EXCHANGE_ECDH_ANON_ENABLED */
2358 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2359     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
2360     {
2361         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
2362                                               p, end - p );
2363         if( ret != 0 )
2364         {
2365             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
2366             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2367         }
2368     }
2369     else
2370 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2371     {
2372         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2373         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2374     }
2375
2376 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2377     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2378     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
2379     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
2380         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2381         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
2382     {
2383         size_t sig_len, hashlen;
2384         unsigned char hash[64];
2385         mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
2386         mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
2387         unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
2388         size_t params_len = p - params;
2389
2390         /*
2391          * Handle the digitally-signed structure
2392          */
2393 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2394         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
2395         {
2396             if( ssl_parse_signature_algorithm( ssl, &p, end,
2397                                                &md_alg, &pk_alg ) != 0 )
2398             {
2399                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2400                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2401             }
2402
2403             if( pk_alg != mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
2404             {
2405                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2406                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2407             }
2408         }
2409         else
2410 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2411 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2412     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2413         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
2414         {
2415             pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
2416
2417             /* Default hash for ECDSA is SHA-1 */
2418             if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
2419                 md_alg = MBEDTLS_MD_SHA1;
2420         }
2421         else
2422 #endif
2423         {
2424             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2425             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2426         }
2427
2428 // Anonim cipher suite without sign, ecdh param only
2429 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ANON_ENABLED)
2430         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
2431         {
2432             goto exit;
2433         }
2434 #endif
2435         /*
2436          * Read signature
2437          */
2438         sig_len = ( p[0] << 8 ) | p[1];
2439         p += 2;
2440
2441         if( end != p + sig_len )
2442         {
2443             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2444             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2445         }
2446
2447         MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
2448
2449         /*
2450          * Compute the hash that has been signed
2451          */
2452 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2453     defined(MBEDTLS_SSL_PROTO_TLS1_1)
2454         if( md_alg == MBEDTLS_MD_NONE )
2455         {
2456             mbedtls_md5_context mbedtls_md5;
2457             mbedtls_sha1_context mbedtls_sha1;
2458
2459             mbedtls_md5_init(  &mbedtls_md5  );
2460             mbedtls_sha1_init( &mbedtls_sha1 );
2461
2462             hashlen = 36;
2463
2464             /*
2465              * digitally-signed struct {
2466              *     opaque md5_hash[16];
2467              *     opaque sha_hash[20];
2468              * };
2469              *
2470              * md5_hash
2471              *     MD5(ClientHello.random + ServerHello.random
2472              *                            + ServerParams);
2473              * sha_hash
2474              *     SHA(ClientHello.random + ServerHello.random
2475              *                            + ServerParams);
2476              */
2477             mbedtls_md5_starts( &mbedtls_md5 );
2478             mbedtls_md5_update( &mbedtls_md5, ssl->handshake->randbytes, 64 );
2479             mbedtls_md5_update( &mbedtls_md5, params, params_len );
2480             mbedtls_md5_finish( &mbedtls_md5, hash );
2481
2482             mbedtls_sha1_starts( &mbedtls_sha1 );
2483             mbedtls_sha1_update( &mbedtls_sha1, ssl->handshake->randbytes, 64 );
2484             mbedtls_sha1_update( &mbedtls_sha1, params, params_len );
2485             mbedtls_sha1_finish( &mbedtls_sha1, hash + 16 );
2486
2487             mbedtls_md5_free(  &mbedtls_md5  );
2488             mbedtls_sha1_free( &mbedtls_sha1 );
2489         }
2490         else
2491 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
2492           MBEDTLS_SSL_PROTO_TLS1_1 */
2493 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2494     defined(MBEDTLS_SSL_PROTO_TLS1_2)
2495         if( md_alg != MBEDTLS_MD_NONE )
2496         {
2497             mbedtls_md_context_t ctx;
2498
2499             mbedtls_md_init( &ctx );
2500
2501             /* Info from md_alg will be used instead */
2502             hashlen = 0;
2503
2504             /*
2505              * digitally-signed struct {
2506              *     opaque client_random[32];
2507              *     opaque server_random[32];
2508              *     ServerDHParams params;
2509              * };
2510              */
2511             if( ( ret = mbedtls_md_setup( &ctx,
2512                                      mbedtls_md_info_from_type( md_alg ), 0 ) ) != 0 )
2513             {
2514                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_md_setup", ret );
2515                 return( ret );
2516             }
2517
2518             mbedtls_md_starts( &ctx );
2519             mbedtls_md_update( &ctx, ssl->handshake->randbytes, 64 );
2520             mbedtls_md_update( &ctx, params, params_len );
2521             mbedtls_md_finish( &ctx, hash );
2522             mbedtls_md_free( &ctx );
2523         }
2524         else
2525 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2526           MBEDTLS_SSL_PROTO_TLS1_2 */
2527         {
2528             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2529             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2530         }
2531
2532         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen != 0 ? hashlen :
2533             (unsigned int) ( mbedtls_md_get_size( mbedtls_md_info_from_type( md_alg ) ) ) );
2534
2535         if( ssl->session_negotiate->peer_cert == NULL )
2536         {
2537             MBEDTLS_SSL_DEBUG_MSG( 2, ( "certificate required" ) );
2538             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2539         }
2540
2541         /*
2542          * Verify signature
2543          */
2544         if( ! mbedtls_pk_can_do( &ssl->session_negotiate->peer_cert->pk, pk_alg ) )
2545         {
2546             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
2547             return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2548         }
2549
2550         if( ( ret = mbedtls_pk_verify( &ssl->session_negotiate->peer_cert->pk,
2551                                md_alg, hash, hashlen, p, sig_len ) ) != 0 )
2552         {
2553             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
2554             return( ret );
2555         }
2556     }
2557 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2558           MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2559           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2560
2561 exit:
2562     ssl->state++;
2563
2564     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
2565
2566     return( 0 );
2567 }
2568
2569 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
2570     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
2571     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \
2572     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
2573     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
2574     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
2575 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
2576 {
2577     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
2578
2579     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
2580
2581     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2582         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
2583         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2584         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
2585         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
2586         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
2587     {
2588         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
2589         ssl->state++;
2590         return( 0 );
2591     }
2592
2593     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2594     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2595 }
2596 #else
2597 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
2598 {
2599     int ret;
2600     unsigned char *buf;
2601     size_t n = 0;
2602     size_t cert_type_len = 0, dn_len = 0;
2603     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
2604
2605     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
2606
2607     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2608         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
2609         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2610         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
2611         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
2612         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
2613     {
2614         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
2615         ssl->state++;
2616         return( 0 );
2617     }
2618
2619     if( ssl->record_read == 0 )
2620     {
2621         if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
2622         {
2623             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2624             return( ret );
2625         }
2626
2627         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2628         {
2629             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2630             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2631         }
2632
2633         ssl->record_read = 1;
2634     }
2635
2636     ssl->client_auth = 0;
2637     ssl->state++;
2638
2639     if( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST )
2640         ssl->client_auth++;
2641
2642     MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
2643                         ssl->client_auth ? "a" : "no" ) );
2644
2645     if( ssl->client_auth == 0 )
2646         goto exit;
2647
2648     ssl->record_read = 0;
2649
2650     /*
2651      *  struct {
2652      *      ClientCertificateType certificate_types<1..2^8-1>;
2653      *      SignatureAndHashAlgorithm
2654      *        supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
2655      *      DistinguishedName certificate_authorities<0..2^16-1>;
2656      *  } CertificateRequest;
2657      *
2658      *  Since we only support a single certificate on clients, let's just
2659      *  ignore all the information that's supposed to help us pick a
2660      *  certificate.
2661      *
2662      *  We could check that our certificate matches the request, and bail out
2663      *  if it doesn't, but it's simpler to just send the certificate anyway,
2664      *  and give the server the opportunity to decide if it should terminate
2665      *  the connection when it doesn't like our certificate.
2666      *
2667      *  Same goes for the hash in TLS 1.2's signature_algorithms: at this
2668      *  point we only have one hash available (see comments in
2669      *  write_certificate_verify), so let's just use what we have.
2670      *
2671      *  However, we still minimally parse the message to check it is at least
2672      *  superficially sane.
2673      */
2674     buf = ssl->in_msg;
2675
2676     /* certificate_types */
2677     cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
2678     n = cert_type_len;
2679
2680     if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
2681     {
2682         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2683         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
2684     }
2685
2686     /* supported_signature_algorithms */
2687 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2688     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
2689     {
2690         size_t sig_alg_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
2691                              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
2692 #if defined(MBEDTLS_DEBUG_C)
2693         unsigned char* sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
2694         size_t i;
2695
2696         for( i = 0; i < sig_alg_len; i += 2 )
2697         {
2698             MBEDTLS_SSL_DEBUG_MSG( 3, ( "Supported Signature Algorithm found: %d,%d", sig_alg[i], sig_alg[i + 1]  ) );
2699         }
2700 #endif
2701
2702         n += 2 + sig_alg_len;
2703
2704         if( ssl->in_hslen < mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
2705         {
2706             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2707             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
2708         }
2709     }
2710 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2711
2712     /* certificate_authorities */
2713     dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
2714              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
2715
2716     n += dn_len;
2717     if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
2718     {
2719         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
2720         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
2721     }
2722
2723 exit:
2724     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
2725
2726     return( 0 );
2727 }
2728 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
2729           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
2730           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
2731           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
2732           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
2733           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2734
2735 static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
2736 {
2737     int ret;
2738
2739     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
2740
2741     if( ssl->record_read == 0 )
2742     {
2743         if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
2744         {
2745             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2746             return( ret );
2747         }
2748
2749         if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2750         {
2751             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
2752             return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2753         }
2754     }
2755     ssl->record_read = 0;
2756
2757     if( ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ||
2758         ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
2759     {
2760         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
2761         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
2762     }
2763
2764     ssl->state++;
2765
2766 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2767     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2768         mbedtls_ssl_recv_flight_completed( ssl );
2769 #endif
2770
2771     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
2772
2773     return( 0 );
2774 }
2775
2776 static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
2777 {
2778     int ret;
2779     size_t i, n;
2780     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
2781
2782     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
2783
2784 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
2785     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
2786     {
2787         /*
2788          * DHM key exchange -- send G^X mod P
2789          */
2790         n = ssl->handshake->dhm_ctx.len;
2791
2792         ssl->out_msg[4] = (unsigned char)( n >> 8 );
2793         ssl->out_msg[5] = (unsigned char)( n      );
2794         i = 6;
2795
2796         ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
2797                                 (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
2798                                &ssl->out_msg[i], n,
2799                                 ssl->conf->f_rng, ssl->conf->p_rng );
2800         if( ret != 0 )
2801         {
2802             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
2803             return( ret );
2804         }
2805
2806         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
2807         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
2808
2809         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
2810                                       ssl->handshake->premaster,
2811                                       MBEDTLS_PREMASTER_SIZE,
2812                                      &ssl->handshake->pmslen,
2813                                       ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2814         {
2815             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
2816             return( ret );
2817         }
2818
2819         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
2820     }
2821     else
2822 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
2823 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2824     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2825     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
2826     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) ||                    \
2827     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ANON_ENABLED)
2828     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
2829         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
2830         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
2831         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ||
2832         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON)
2833     {
2834         /*
2835          * ECDH key exchange -- send client public value
2836          */
2837         i = 4;
2838
2839         ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
2840                                 &n,
2841                                 &ssl->out_msg[i], 1000,
2842                                 ssl->conf->f_rng, ssl->conf->p_rng );
2843         if( ret != 0 )
2844         {
2845             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
2846             return( ret );
2847         }
2848
2849         MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
2850
2851         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
2852                                       &ssl->handshake->pmslen,
2853                                        ssl->handshake->premaster,
2854                                        MBEDTLS_MPI_MAX_SIZE,
2855                                        ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2856         {
2857             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
2858             return( ret );
2859         }
2860
2861         MBEDTLS_SSL_DEBUG_MPI( 3, "ECDH: z", &ssl->handshake->ecdh_ctx.z );
2862     }
2863     else
2864 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2865           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2866           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2867           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED
2868           MBEDTLS_KEY_EXCHANGE_ECDH_ANON_ENABLED */
2869 #if defined(MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED)
2870     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
2871         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
2872         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2873         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
2874     {
2875         /*
2876          * opaque psk_identity<0..2^16-1>;
2877          */
2878         if( ssl->conf->psk == NULL || ssl->conf->psk_identity == NULL )
2879         {
2880             MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for PSK" ) );
2881             return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
2882         }
2883
2884         i = 4;
2885         n = ssl->conf->psk_identity_len;
2886
2887         if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
2888         {
2889             MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity too long or "
2890                                         "SSL buffer too short" ) );
2891             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2892         }
2893
2894         ssl->out_msg[i++] = (unsigned char)( n >> 8 );
2895         ssl->out_msg[i++] = (unsigned char)( n      );
2896
2897         memcpy( ssl->out_msg + i, ssl->conf->psk_identity, ssl->conf->psk_identity_len );
2898         i += ssl->conf->psk_identity_len;
2899
2900 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
2901         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
2902         {
2903             n = 0;
2904         }
2905         else
2906 #endif
2907 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2908         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
2909         {
2910             if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 2 ) ) != 0 )
2911                 return( ret );
2912         }
2913         else
2914 #endif
2915 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
2916         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
2917         {
2918             /*
2919              * ClientDiffieHellmanPublic public (DHM send G^X mod P)
2920              */
2921             n = ssl->handshake->dhm_ctx.len;
2922
2923             if( i + 2 + n > MBEDTLS_SSL_MAX_CONTENT_LEN )
2924             {
2925                 MBEDTLS_SSL_DEBUG_MSG( 1, ( "psk identity or DHM size too long"
2926                                             " or SSL buffer too short" ) );
2927                 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2928             }
2929
2930             ssl->out_msg[i++] = (unsigned char)( n >> 8 );
2931             ssl->out_msg[i++] = (unsigned char)( n      );
2932
2933             ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
2934                     (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
2935                     &ssl->out_msg[i], n,
2936                     ssl->conf->f_rng, ssl->conf->p_rng );
2937             if( ret != 0 )
2938             {
2939                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
2940                 return( ret );
2941             }
2942         }
2943         else
2944 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2945 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
2946         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
2947         {
2948             /*
2949              * ClientECDiffieHellmanPublic public;
2950              */
2951             ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx, &n,
2952                     &ssl->out_msg[i], MBEDTLS_SSL_MAX_CONTENT_LEN - i,
2953                     ssl->conf->f_rng, ssl->conf->p_rng );
2954             if( ret != 0 )
2955             {
2956                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
2957                 return( ret );
2958             }
2959
2960             MBEDTLS_SSL_DEBUG_ECP( 3, "ECDH: Q", &ssl->handshake->ecdh_ctx.Q );
2961         }
2962         else
2963 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
2964         {
2965             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2966             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2967         }
2968
2969         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
2970                         ciphersuite_info->key_exchange ) ) != 0 )
2971         {
2972             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret );
2973             return( ret );
2974         }
2975     }
2976     else
2977 #endif /* MBEDTLS_KEY_EXCHANGE__SOME__PSK_ENABLED */
2978 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
2979     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
2980     {
2981         i = 4;
2982         if( ( ret = ssl_write_encrypted_pms( ssl, i, &n, 0 ) ) != 0 )
2983             return( ret );
2984     }
2985     else
2986 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
2987 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2988     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
2989     {
2990         i = 4;
2991
2992         ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
2993                 ssl->out_msg + i, MBEDTLS_SSL_MAX_CONTENT_LEN - i, &n,
2994                 ssl->conf->f_rng, ssl->conf->p_rng );
2995         if( ret != 0 )
2996         {
2997             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
2998             return( ret );
2999         }
3000
3001         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
3002                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
3003                 ssl->conf->f_rng, ssl->conf->p_rng );
3004         if( ret != 0 )
3005         {
3006             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
3007             return( ret );
3008         }
3009     }
3010     else
3011 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
3012     {
3013         ((void) ciphersuite_info);
3014         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3015         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3016     }
3017
3018     ssl->out_msglen  = i + n;
3019     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3020     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
3021
3022     ssl->state++;
3023
3024     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
3025     {
3026         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
3027         return( ret );
3028     }
3029
3030     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
3031
3032     return( 0 );
3033 }
3034
3035 #if !defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)       && \
3036     !defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)   && \
3037     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)  && \
3038     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
3039     !defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)&& \
3040     !defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
3041 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
3042 {
3043     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
3044     int ret;
3045
3046     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
3047
3048     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
3049     {
3050         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
3051         return( ret );
3052     }
3053
3054     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
3055         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3056         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
3057         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
3058         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
3059         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
3060     {
3061         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3062         ssl->state++;
3063         return( 0 );
3064     }
3065
3066     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3067     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3068 }
3069 #else
3070 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
3071 {
3072     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3073     const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->transform_negotiate->ciphersuite_info;
3074     size_t n = 0, offset = 0;
3075     unsigned char hash[48];
3076     unsigned char *hash_start = hash;
3077     mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
3078     unsigned int hashlen;
3079
3080     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
3081
3082     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
3083     {
3084         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
3085         return( ret );
3086     }
3087
3088     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
3089         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3090         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
3091         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
3092         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ||
3093         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ANON )
3094     {
3095         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3096         ssl->state++;
3097         return( 0 );
3098     }
3099
3100     if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
3101     {
3102         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
3103         ssl->state++;
3104         return( 0 );
3105     }
3106
3107     if( mbedtls_ssl_own_key( ssl ) == NULL )
3108     {
3109         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
3110         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
3111     }
3112
3113     /*
3114      * Make an RSA signature of the handshake digests
3115      */
3116     ssl->handshake->calc_verify( ssl, hash );
3117
3118 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3119     defined(MBEDTLS_SSL_PROTO_TLS1_1)
3120     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
3121     {
3122         /*
3123          * digitally-signed struct {
3124          *     opaque md5_hash[16];
3125          *     opaque sha_hash[20];
3126          * };
3127          *
3128          * md5_hash
3129          *     MD5(handshake_messages);
3130          *
3131          * sha_hash
3132          *     SHA(handshake_messages);
3133          */
3134         hashlen = 36;
3135         md_alg = MBEDTLS_MD_NONE;
3136
3137         /*
3138          * For ECDSA, default hash is SHA-1 only
3139          */
3140         if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
3141         {
3142             hash_start += 16;
3143             hashlen -= 16;
3144             md_alg = MBEDTLS_MD_SHA1;
3145         }
3146     }
3147     else
3148 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
3149           MBEDTLS_SSL_PROTO_TLS1_1 */
3150 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3151     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
3152     {
3153         /*
3154          * digitally-signed struct {
3155          *     opaque handshake_messages[handshake_messages_length];
3156          * };
3157          *
3158          * Taking shortcut here. We assume that the server always allows the
3159          * PRF Hash function and has sent it in the allowed signature
3160          * algorithms list received in the Certificate Request message.
3161          *
3162          * Until we encounter a server that does not, we will take this
3163          * shortcut.
3164          *
3165          * Reason: Otherwise we should have running hashes for SHA512 and SHA224
3166          *         in order to satisfy 'weird' needs from the server side.
3167          */
3168         if( ssl->transform_negotiate->ciphersuite_info->mac ==
3169             MBEDTLS_MD_SHA384 )
3170         {
3171             md_alg = MBEDTLS_MD_SHA384;
3172             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
3173         }
3174         else
3175         {
3176             md_alg = MBEDTLS_MD_SHA256;
3177             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
3178         }
3179         ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
3180
3181         /* Info from md_alg will be used instead */
3182         hashlen = 0;
3183         offset = 2;
3184     }
3185     else
3186 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3187     {
3188         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3189         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3190     }
3191
3192     if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash_start, hashlen,
3193                          ssl->out_msg + 6 + offset, &n,
3194                          ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3195     {
3196         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
3197         return( ret );
3198     }
3199
3200     ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
3201     ssl->out_msg[5 + offset] = (unsigned char)( n      );
3202
3203     ssl->out_msglen  = 6 + n + offset;
3204     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3205     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
3206
3207     ssl->state++;
3208
3209     if( ( ret = mbedtls_ssl_write_record( ssl ) ) != 0 )
3210     {
3211         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_record", ret );
3212         return( ret );
3213     }
3214
3215     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
3216
3217     return( ret );
3218 }
3219 #endif /* !MBEDTLS_KEY_EXCHANGE_RSA_ENABLED &&
3220           !MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED &&
3221           !MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED &&
3222           !MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED &&
3223           !MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED &&
3224           !MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
3225
3226 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3227 static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
3228 {
3229     int ret;
3230     uint32_t lifetime;
3231     size_t ticket_len;
3232     unsigned char *ticket;
3233     const unsigned char *msg;
3234
3235     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
3236
3237     if( ( ret = mbedtls_ssl_read_record( ssl ) ) != 0 )
3238     {
3239         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
3240         return( ret );
3241     }
3242
3243     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
3244     {
3245         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3246         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3247     }
3248
3249     /*
3250      * struct {
3251      *     uint32 ticket_lifetime_hint;
3252      *     opaque ticket<0..2^16-1>;
3253      * } NewSessionTicket;
3254      *
3255      * 0  .  3   ticket_lifetime_hint
3256      * 4  .  5   ticket_len (n)
3257      * 6  .  5+n ticket content
3258      */
3259     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
3260         ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
3261     {
3262         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3263         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
3264     }
3265
3266     msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
3267
3268     lifetime = ( msg[0] << 24 ) | ( msg[1] << 16 ) |
3269                ( msg[2] <<  8 ) | ( msg[3]       );
3270
3271     ticket_len = ( msg[4] << 8 ) | ( msg[5] );
3272
3273     if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
3274     {
3275         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
3276         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
3277     }
3278
3279     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
3280
3281     /* We're not waiting for a NewSessionTicket message any more */
3282     ssl->handshake->new_session_ticket = 0;
3283     ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
3284
3285     /*
3286      * Zero-length ticket means the server changed his mind and doesn't want
3287      * to send a ticket after all, so just forget it
3288      */
3289     if( ticket_len == 0 )
3290         return( 0 );
3291
3292     mbedtls_zeroize( ssl->session_negotiate->ticket,
3293                       ssl->session_negotiate->ticket_len );
3294     mbedtls_free( ssl->session_negotiate->ticket );
3295     ssl->session_negotiate->ticket = NULL;
3296     ssl->session_negotiate->ticket_len = 0;
3297
3298     if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
3299     {
3300         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
3301         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
3302     }
3303
3304     memcpy( ticket, msg + 6, ticket_len );
3305
3306     ssl->session_negotiate->ticket = ticket;
3307     ssl->session_negotiate->ticket_len = ticket_len;
3308     ssl->session_negotiate->ticket_lifetime = lifetime;
3309
3310     /*
3311      * RFC 5077 section 3.4:
3312      * "If the client receives a session ticket from the server, then it
3313      * discards any Session ID that was sent in the ServerHello."
3314      */
3315     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
3316     ssl->session_negotiate->id_len = 0;
3317
3318     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
3319
3320     return( 0 );
3321 }
3322 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
3323
3324 /*
3325  * SSL handshake -- client side -- single step
3326  */
3327 int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
3328 {
3329     int ret = 0;
3330
3331     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
3332         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3333
3334     MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
3335
3336     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
3337         return( ret );
3338
3339 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3340     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3341         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
3342     {
3343         if( ( ret = mbedtls_ssl_resend( ssl ) ) != 0 )
3344             return( ret );
3345     }
3346 #endif
3347
3348     /* Change state now, so that it is right in mbedtls_ssl_read_record(), used
3349      * by DTLS for dropping out-of-sequence ChangeCipherSpec records */
3350 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3351     if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
3352         ssl->handshake->new_session_ticket != 0 )
3353     {
3354         ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
3355     }
3356 #endif
3357
3358     switch( ssl->state )
3359     {
3360         case MBEDTLS_SSL_HELLO_REQUEST:
3361             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
3362             break;
3363
3364        /*
3365         *  ==>   ClientHello
3366         */
3367        case MBEDTLS_SSL_CLIENT_HELLO:
3368            ret = ssl_write_client_hello( ssl );
3369            break;
3370
3371        /*
3372         *  <==   ServerHello
3373         *        Certificate
3374         *      ( ServerKeyExchange  )
3375         *      ( CertificateRequest )
3376         *        ServerHelloDone
3377         */
3378        case MBEDTLS_SSL_SERVER_HELLO:
3379            ret = ssl_parse_server_hello( ssl );
3380            break;
3381
3382        case MBEDTLS_SSL_SERVER_CERTIFICATE:
3383            ret = mbedtls_ssl_parse_certificate( ssl );
3384            break;
3385
3386        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
3387            ret = ssl_parse_server_key_exchange( ssl );
3388            break;
3389
3390        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
3391            ret = ssl_parse_certificate_request( ssl );
3392            break;
3393
3394        case MBEDTLS_SSL_SERVER_HELLO_DONE:
3395            ret = ssl_parse_server_hello_done( ssl );
3396            break;
3397
3398        /*
3399         *  ==> ( Certificate/Alert  )
3400         *        ClientKeyExchange
3401         *      ( CertificateVerify  )
3402         *        ChangeCipherSpec
3403         *        Finished
3404         */
3405        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
3406            ret = mbedtls_ssl_write_certificate( ssl );
3407            break;
3408
3409        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
3410            ret = ssl_write_client_key_exchange( ssl );
3411            break;
3412
3413        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
3414            ret = ssl_write_certificate_verify( ssl );
3415            break;
3416
3417        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
3418            ret = mbedtls_ssl_write_change_cipher_spec( ssl );
3419            break;
3420
3421        case MBEDTLS_SSL_CLIENT_FINISHED:
3422            ret = mbedtls_ssl_write_finished( ssl );
3423            break;
3424
3425        /*
3426         *  <==   ( NewSessionTicket )
3427         *        ChangeCipherSpec
3428         *        Finished
3429         */
3430 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
3431        case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
3432            ret = ssl_parse_new_session_ticket( ssl );
3433            break;
3434 #endif
3435
3436        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
3437            ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
3438            break;
3439
3440        case MBEDTLS_SSL_SERVER_FINISHED:
3441            ret = mbedtls_ssl_parse_finished( ssl );
3442            break;
3443
3444        case MBEDTLS_SSL_FLUSH_BUFFERS:
3445            MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
3446            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3447            break;
3448
3449        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
3450            mbedtls_ssl_handshake_wrapup( ssl );
3451            break;
3452
3453        default:
3454            MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
3455            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
3456    }
3457
3458     return( ret );
3459 }
3460 #endif /* MBEDTLS_SSL_CLI_C */