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