1 /*
2  *  SSLv3/TLSv1 client-side functions
3  *
4  *  Copyright The Mbed TLS Contributors
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 
20 #include "common.h"
21 
22 #if defined(MBEDTLS_SSL_CLI_C)
23 
24 #if defined(MBEDTLS_PLATFORM_C)
25 #include "mbedtls/platform.h"
26 #else
27 #include <stdlib.h>
28 #define mbedtls_calloc    calloc
29 #define mbedtls_free      free
30 #endif
31 
32 #include "mbedtls/ssl.h"
33 #include "mbedtls/ssl_internal.h"
34 #include "mbedtls/debug.h"
35 #include "mbedtls/error.h"
36 
37 #if defined(MBEDTLS_USE_PSA_CRYPTO)
38 #include "mbedtls/psa_util.h"
39 #endif /* MBEDTLS_USE_PSA_CRYPTO */
40 
41 #include <string.h>
42 
43 #include <stdint.h>
44 
45 #if defined(MBEDTLS_HAVE_TIME)
46 #include "mbedtls/platform_time.h"
47 #endif
48 
49 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
50 #include "mbedtls/platform_util.h"
51 #endif
52 
53 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
ssl_conf_has_static_psk(mbedtls_ssl_config const * conf)54 static int ssl_conf_has_static_psk( mbedtls_ssl_config const *conf )
55 {
56     if( conf->psk_identity     == NULL ||
57         conf->psk_identity_len == 0     )
58     {
59         return( 0 );
60     }
61 
62     if( conf->psk != NULL && conf->psk_len != 0 )
63         return( 1 );
64 
65 #if defined(MBEDTLS_USE_PSA_CRYPTO)
66     if( ! mbedtls_svc_key_id_is_null( conf->psk_opaque ) )
67         return( 1 );
68 #endif /* MBEDTLS_USE_PSA_CRYPTO */
69 
70     return( 0 );
71 }
72 
73 #if defined(MBEDTLS_USE_PSA_CRYPTO)
ssl_conf_has_static_raw_psk(mbedtls_ssl_config const * conf)74 static int ssl_conf_has_static_raw_psk( mbedtls_ssl_config const *conf )
75 {
76     if( conf->psk_identity     == NULL ||
77         conf->psk_identity_len == 0     )
78     {
79         return( 0 );
80     }
81 
82     if( conf->psk != NULL && conf->psk_len != 0 )
83         return( 1 );
84 
85     return( 0 );
86 }
87 #endif /* MBEDTLS_USE_PSA_CRYPTO */
88 
89 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
90 
91 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
ssl_write_hostname_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)92 static int ssl_write_hostname_ext( mbedtls_ssl_context *ssl,
93                                    unsigned char *buf,
94                                    const unsigned char *end,
95                                    size_t *olen )
96 {
97     unsigned char *p = buf;
98     size_t hostname_len;
99 
100     *olen = 0;
101 
102     if( ssl->hostname == NULL )
103         return( 0 );
104 
105     MBEDTLS_SSL_DEBUG_MSG( 3,
106         ( "client hello, adding server name extension: %s",
107           ssl->hostname ) );
108 
109     hostname_len = strlen( ssl->hostname );
110 
111     MBEDTLS_SSL_CHK_BUF_PTR( p, end, hostname_len + 9 );
112 
113     /*
114      * Sect. 3, RFC 6066 (TLS Extensions Definitions)
115      *
116      * In order to provide any of the server names, clients MAY include an
117      * extension of type "server_name" in the (extended) client hello. The
118      * "extension_data" field of this extension SHALL contain
119      * "ServerNameList" where:
120      *
121      * struct {
122      *     NameType name_type;
123      *     select (name_type) {
124      *         case host_name: HostName;
125      *     } name;
126      * } ServerName;
127      *
128      * enum {
129      *     host_name(0), (255)
130      * } NameType;
131      *
132      * opaque HostName<1..2^16-1>;
133      *
134      * struct {
135      *     ServerName server_name_list<1..2^16-1>
136      * } ServerNameList;
137      *
138      */
139     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME >> 8 ) & 0xFF );
140     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME      ) & 0xFF );
141 
142     *p++ = (unsigned char)( ( (hostname_len + 5) >> 8 ) & 0xFF );
143     *p++ = (unsigned char)( ( (hostname_len + 5)      ) & 0xFF );
144 
145     *p++ = (unsigned char)( ( (hostname_len + 3) >> 8 ) & 0xFF );
146     *p++ = (unsigned char)( ( (hostname_len + 3)      ) & 0xFF );
147 
148     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) & 0xFF );
149     *p++ = (unsigned char)( ( hostname_len >> 8 ) & 0xFF );
150     *p++ = (unsigned char)( ( hostname_len      ) & 0xFF );
151 
152     memcpy( p, ssl->hostname, hostname_len );
153 
154     *olen = hostname_len + 9;
155 
156     return( 0 );
157 }
158 #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
159 
160 #if defined(MBEDTLS_SSL_RENEGOTIATION)
ssl_write_renegotiation_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)161 static int ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl,
162                                         unsigned char *buf,
163                                         const unsigned char *end,
164                                         size_t *olen )
165 {
166     unsigned char *p = buf;
167 
168     *olen = 0;
169 
170     /* We're always including an TLS_EMPTY_RENEGOTIATION_INFO_SCSV in the
171      * initial ClientHello, in which case also adding the renegotiation
172      * info extension is NOT RECOMMENDED as per RFC 5746 Section 3.4. */
173     if( ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
174         return( 0 );
175 
176     MBEDTLS_SSL_DEBUG_MSG( 3,
177         ( "client hello, adding renegotiation extension" ) );
178 
179     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 + ssl->verify_data_len );
180 
181     /*
182      * Secure renegotiation
183      */
184     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 )
185                             & 0xFF );
186     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO      )
187                             & 0xFF );
188 
189     *p++ = 0x00;
190     *p++ = ( ssl->verify_data_len + 1 ) & 0xFF;
191     *p++ = ssl->verify_data_len & 0xFF;
192 
193     memcpy( p, ssl->own_verify_data, ssl->verify_data_len );
194 
195     *olen = 5 + ssl->verify_data_len;
196 
197     return( 0 );
198 }
199 #endif /* MBEDTLS_SSL_RENEGOTIATION */
200 
201 /*
202  * Only if we handle at least one key exchange that needs signatures.
203  */
204 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
205     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
ssl_write_signature_algorithms_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)206 static int ssl_write_signature_algorithms_ext( mbedtls_ssl_context *ssl,
207                                                unsigned char *buf,
208                                                const unsigned char *end,
209                                                size_t *olen )
210 {
211     unsigned char *p = buf;
212     size_t sig_alg_len = 0;
213     const int *md;
214 
215 #if defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C)
216     unsigned char *sig_alg_list = buf + 6;
217 #endif
218 
219     *olen = 0;
220 
221     if( ssl->conf->max_minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
222         return( 0 );
223 
224     MBEDTLS_SSL_DEBUG_MSG( 3,
225         ( "client hello, adding signature_algorithms extension" ) );
226 
227     if( ssl->conf->sig_hashes == NULL )
228         return( MBEDTLS_ERR_SSL_BAD_CONFIG );
229 
230     for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
231     {
232 #if defined(MBEDTLS_ECDSA_C)
233         sig_alg_len += 2;
234 #endif
235 #if defined(MBEDTLS_RSA_C)
236         sig_alg_len += 2;
237 #endif
238         if( sig_alg_len > MBEDTLS_SSL_MAX_SIG_HASH_ALG_LIST_LEN )
239         {
240             MBEDTLS_SSL_DEBUG_MSG( 3,
241                 ( "length in bytes of sig-hash-alg extension too big" ) );
242             return( MBEDTLS_ERR_SSL_BAD_CONFIG );
243         }
244     }
245 
246     /* Empty signature algorithms list, this is a configuration error. */
247     if( sig_alg_len == 0 )
248         return( MBEDTLS_ERR_SSL_BAD_CONFIG );
249 
250     MBEDTLS_SSL_CHK_BUF_PTR( p, end, sig_alg_len + 6 );
251 
252     /*
253      * Prepare signature_algorithms extension (TLS 1.2)
254      */
255     sig_alg_len = 0;
256 
257     for( md = ssl->conf->sig_hashes; *md != MBEDTLS_MD_NONE; md++ )
258     {
259 #if defined(MBEDTLS_ECDSA_C)
260         sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
261         sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_ECDSA;
262 #endif
263 #if defined(MBEDTLS_RSA_C)
264         sig_alg_list[sig_alg_len++] = mbedtls_ssl_hash_from_md_alg( *md );
265         sig_alg_list[sig_alg_len++] = MBEDTLS_SSL_SIG_RSA;
266 #endif
267     }
268 
269     /*
270      * enum {
271      *     none(0), md5(1), sha1(2), sha224(3), sha256(4), sha384(5),
272      *     sha512(6), (255)
273      * } HashAlgorithm;
274      *
275      * enum { anonymous(0), rsa(1), dsa(2), ecdsa(3), (255) }
276      *   SignatureAlgorithm;
277      *
278      * struct {
279      *     HashAlgorithm hash;
280      *     SignatureAlgorithm signature;
281      * } SignatureAndHashAlgorithm;
282      *
283      * SignatureAndHashAlgorithm
284      *   supported_signature_algorithms<2..2^16-2>;
285      */
286     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG >> 8 ) & 0xFF );
287     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SIG_ALG      ) & 0xFF );
288 
289     *p++ = (unsigned char)( ( ( sig_alg_len + 2 ) >> 8 ) & 0xFF );
290     *p++ = (unsigned char)( ( ( sig_alg_len + 2 )      ) & 0xFF );
291 
292     *p++ = (unsigned char)( ( sig_alg_len >> 8 ) & 0xFF );
293     *p++ = (unsigned char)( ( sig_alg_len      ) & 0xFF );
294 
295     *olen = 6 + sig_alg_len;
296 
297     return( 0 );
298 }
299 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 &&
300           MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
301 
302 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
303     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_supported_elliptic_curves_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)304 static int ssl_write_supported_elliptic_curves_ext( mbedtls_ssl_context *ssl,
305                                                     unsigned char *buf,
306                                                     const unsigned char *end,
307                                                     size_t *olen )
308 {
309     unsigned char *p = buf;
310     unsigned char *elliptic_curve_list = p + 6;
311     size_t elliptic_curve_len = 0;
312     const mbedtls_ecp_curve_info *info;
313     const mbedtls_ecp_group_id *grp_id;
314 
315     *olen = 0;
316 
317     MBEDTLS_SSL_DEBUG_MSG( 3,
318         ( "client hello, adding supported_elliptic_curves extension" ) );
319 
320     if( ssl->conf->curve_list == NULL )
321         return( MBEDTLS_ERR_SSL_BAD_CONFIG );
322 
323     for( grp_id = ssl->conf->curve_list;
324          *grp_id != MBEDTLS_ECP_DP_NONE;
325          grp_id++ )
326     {
327         info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
328         if( info == NULL )
329         {
330             MBEDTLS_SSL_DEBUG_MSG( 1,
331                 ( "invalid curve in ssl configuration" ) );
332             return( MBEDTLS_ERR_SSL_BAD_CONFIG );
333         }
334         elliptic_curve_len += 2;
335 
336         if( elliptic_curve_len > MBEDTLS_SSL_MAX_CURVE_LIST_LEN )
337         {
338             MBEDTLS_SSL_DEBUG_MSG( 3,
339                 ( "malformed supported_elliptic_curves extension in config" ) );
340             return( MBEDTLS_ERR_SSL_BAD_CONFIG );
341         }
342     }
343 
344     /* Empty elliptic curve list, this is a configuration error. */
345     if( elliptic_curve_len == 0 )
346         return( MBEDTLS_ERR_SSL_BAD_CONFIG );
347 
348     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + elliptic_curve_len );
349 
350     elliptic_curve_len = 0;
351 
352     for( grp_id = ssl->conf->curve_list;
353          *grp_id != MBEDTLS_ECP_DP_NONE;
354          grp_id++ )
355     {
356         info = mbedtls_ecp_curve_info_from_grp_id( *grp_id );
357         elliptic_curve_list[elliptic_curve_len++] = info->tls_id >> 8;
358         elliptic_curve_list[elliptic_curve_len++] = info->tls_id & 0xFF;
359     }
360 
361     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES >> 8 )
362                             & 0xFF );
363     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES      )
364                             & 0xFF );
365 
366     *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 ) >> 8 ) & 0xFF );
367     *p++ = (unsigned char)( ( ( elliptic_curve_len + 2 )      ) & 0xFF );
368 
369     *p++ = (unsigned char)( ( ( elliptic_curve_len     ) >> 8 ) & 0xFF );
370     *p++ = (unsigned char)( ( ( elliptic_curve_len     )      ) & 0xFF );
371 
372     *olen = 6 + elliptic_curve_len;
373 
374     return( 0 );
375 }
376 
ssl_write_supported_point_formats_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)377 static int ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl,
378                                                   unsigned char *buf,
379                                                   const unsigned char *end,
380                                                   size_t *olen )
381 {
382     unsigned char *p = buf;
383     (void) ssl; /* ssl used for debugging only */
384 
385     *olen = 0;
386 
387     MBEDTLS_SSL_DEBUG_MSG( 3,
388         ( "client hello, adding supported_point_formats extension" ) );
389     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 );
390 
391     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 )
392                             & 0xFF );
393     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS      )
394                             & 0xFF );
395 
396     *p++ = 0x00;
397     *p++ = 2;
398 
399     *p++ = 1;
400     *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
401 
402     *olen = 6;
403 
404     return( 0 );
405 }
406 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
407           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
408 
409 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)410 static int ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl,
411                                        unsigned char *buf,
412                                        const unsigned char *end,
413                                        size_t *olen )
414 {
415     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
416     unsigned char *p = buf;
417     size_t kkpp_len;
418 
419     *olen = 0;
420 
421     /* Skip costly extension if we can't use EC J-PAKE anyway */
422     if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
423         return( 0 );
424 
425     MBEDTLS_SSL_DEBUG_MSG( 3,
426         ( "client hello, adding ecjpake_kkpp extension" ) );
427 
428     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 );
429 
430     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF );
431     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP      ) & 0xFF );
432 
433     /*
434      * We may need to send ClientHello multiple times for Hello verification.
435      * We don't want to compute fresh values every time (both for performance
436      * and consistency reasons), so cache the extension content.
437      */
438     if( ssl->handshake->ecjpake_cache == NULL ||
439         ssl->handshake->ecjpake_cache_len == 0 )
440     {
441         MBEDTLS_SSL_DEBUG_MSG( 3, ( "generating new ecjpake parameters" ) );
442 
443         ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx,
444                                                p + 2, end - p - 2, &kkpp_len,
445                                                ssl->conf->f_rng, ssl->conf->p_rng );
446         if( ret != 0 )
447         {
448             MBEDTLS_SSL_DEBUG_RET( 1 ,
449                 "mbedtls_ecjpake_write_round_one", ret );
450             return( ret );
451         }
452 
453         ssl->handshake->ecjpake_cache = mbedtls_calloc( 1, kkpp_len );
454         if( ssl->handshake->ecjpake_cache == NULL )
455         {
456             MBEDTLS_SSL_DEBUG_MSG( 1, ( "allocation failed" ) );
457             return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
458         }
459 
460         memcpy( ssl->handshake->ecjpake_cache, p + 2, kkpp_len );
461         ssl->handshake->ecjpake_cache_len = kkpp_len;
462     }
463     else
464     {
465         MBEDTLS_SSL_DEBUG_MSG( 3, ( "re-using cached ecjpake parameters" ) );
466 
467         kkpp_len = ssl->handshake->ecjpake_cache_len;
468         MBEDTLS_SSL_CHK_BUF_PTR( p + 2, end, kkpp_len );
469 
470         memcpy( p + 2, ssl->handshake->ecjpake_cache, kkpp_len );
471     }
472 
473     *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF );
474     *p++ = (unsigned char)( ( kkpp_len      ) & 0xFF );
475 
476     *olen = kkpp_len + 4;
477 
478     return( 0 );
479 }
480 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
481 
482 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
ssl_write_cid_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)483 static int ssl_write_cid_ext( mbedtls_ssl_context *ssl,
484                               unsigned char *buf,
485                               const unsigned char *end,
486                               size_t *olen )
487 {
488     unsigned char *p = buf;
489     size_t ext_len;
490 
491     /*
492      * Quoting draft-ietf-tls-dtls-connection-id-05
493      * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
494      *
495      *   struct {
496      *      opaque cid<0..2^8-1>;
497      *   } ConnectionId;
498     */
499 
500     *olen = 0;
501     if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
502         ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED )
503     {
504         return( 0 );
505     }
506     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding CID extension" ) );
507 
508     /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX
509      * which is at most 255, so the increment cannot overflow. */
510     MBEDTLS_SSL_CHK_BUF_PTR( p, end, (unsigned)( ssl->own_cid_len + 5 ) );
511 
512     /* Add extension ID + size */
513     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF );
514     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID      ) & 0xFF );
515     ext_len = (size_t) ssl->own_cid_len + 1;
516     *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
517     *p++ = (unsigned char)( ( ext_len      ) & 0xFF );
518 
519     *p++ = (uint8_t) ssl->own_cid_len;
520     memcpy( p, ssl->own_cid, ssl->own_cid_len );
521 
522     *olen = ssl->own_cid_len + 5;
523 
524     return( 0 );
525 }
526 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
527 
528 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_write_max_fragment_length_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)529 static int ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl,
530                                               unsigned char *buf,
531                                               const unsigned char *end,
532                                               size_t *olen )
533 {
534     unsigned char *p = buf;
535 
536     *olen = 0;
537 
538     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE )
539         return( 0 );
540 
541     MBEDTLS_SSL_DEBUG_MSG( 3,
542         ( "client hello, adding max_fragment_length extension" ) );
543 
544     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 5 );
545 
546     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 )
547                             & 0xFF );
548     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH      )
549                             & 0xFF );
550 
551     *p++ = 0x00;
552     *p++ = 1;
553 
554     *p++ = ssl->conf->mfl_code;
555 
556     *olen = 5;
557 
558     return( 0 );
559 }
560 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
561 
562 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_write_truncated_hmac_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)563 static int ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl,
564                                          unsigned char *buf,
565                                          const unsigned char *end,
566                                          size_t *olen )
567 {
568     unsigned char *p = buf;
569 
570     *olen = 0;
571 
572     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED )
573         return( 0 );
574 
575     MBEDTLS_SSL_DEBUG_MSG( 3,
576         ( "client hello, adding truncated_hmac extension" ) );
577 
578     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 );
579 
580     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF );
581     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC      ) & 0xFF );
582 
583     *p++ = 0x00;
584     *p++ = 0x00;
585 
586     *olen = 4;
587 
588     return( 0 );
589 }
590 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
591 
592 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_write_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)593 static int ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
594                                            unsigned char *buf,
595                                            const unsigned char *end,
596                                            size_t *olen )
597 {
598     unsigned char *p = buf;
599 
600     *olen = 0;
601 
602     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
603         ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
604         return( 0 );
605 
606     MBEDTLS_SSL_DEBUG_MSG( 3,
607         ( "client hello, adding encrypt_then_mac extension" ) );
608 
609     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 );
610 
611     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF );
612     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC      ) & 0xFF );
613 
614     *p++ = 0x00;
615     *p++ = 0x00;
616 
617     *olen = 4;
618 
619     return( 0 );
620 }
621 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
622 
623 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_write_extended_ms_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)624 static int ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl,
625                                       unsigned char *buf,
626                                       const unsigned char *end,
627                                       size_t *olen )
628 {
629     unsigned char *p = buf;
630 
631     *olen = 0;
632 
633     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
634         ssl->conf->max_minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 )
635         return( 0 );
636 
637     MBEDTLS_SSL_DEBUG_MSG( 3,
638         ( "client hello, adding extended_master_secret extension" ) );
639 
640     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 );
641 
642     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 )
643                             & 0xFF );
644     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET      )
645                             & 0xFF );
646 
647     *p++ = 0x00;
648     *p++ = 0x00;
649 
650     *olen = 4;
651 
652     return( 0 );
653 }
654 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
655 
656 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_write_session_ticket_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)657 static int ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl,
658                                          unsigned char *buf,
659                                          const unsigned char *end,
660                                          size_t *olen )
661 {
662     unsigned char *p = buf;
663     size_t tlen = ssl->session_negotiate->ticket_len;
664 
665     *olen = 0;
666 
667     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED )
668         return( 0 );
669 
670     MBEDTLS_SSL_DEBUG_MSG( 3,
671         ( "client hello, adding session ticket extension" ) );
672 
673     /* The addition is safe here since the ticket length is 16 bit. */
674     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 4 + tlen );
675 
676     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF );
677     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET      ) & 0xFF );
678 
679     *p++ = (unsigned char)( ( tlen >> 8 ) & 0xFF );
680     *p++ = (unsigned char)( ( tlen      ) & 0xFF );
681 
682     *olen = 4;
683 
684     if( ssl->session_negotiate->ticket == NULL || tlen == 0 )
685         return( 0 );
686 
687     MBEDTLS_SSL_DEBUG_MSG( 3,
688         ( "sending session ticket of length %d", tlen ) );
689 
690     memcpy( p, ssl->session_negotiate->ticket, tlen );
691 
692     *olen += tlen;
693 
694     return( 0 );
695 }
696 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
697 
698 #if defined(MBEDTLS_SSL_ALPN)
ssl_write_alpn_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)699 static int ssl_write_alpn_ext( mbedtls_ssl_context *ssl,
700                                unsigned char *buf,
701                                const unsigned char *end,
702                                size_t *olen )
703 {
704     unsigned char *p = buf;
705     size_t alpnlen = 0;
706     const char **cur;
707 
708     *olen = 0;
709 
710     if( ssl->conf->alpn_list == NULL )
711         return( 0 );
712 
713     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding alpn extension" ) );
714 
715     for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
716         alpnlen += strlen( *cur ) + 1;
717 
718     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 6 + alpnlen );
719 
720     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF );
721     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN      ) & 0xFF );
722 
723     /*
724      * opaque ProtocolName<1..2^8-1>;
725      *
726      * struct {
727      *     ProtocolName protocol_name_list<2..2^16-1>
728      * } ProtocolNameList;
729      */
730 
731     /* Skip writing extension and list length for now */
732     p += 4;
733 
734     for( cur = ssl->conf->alpn_list; *cur != NULL; cur++ )
735     {
736         /*
737          * mbedtls_ssl_conf_set_alpn_protocols() checked that the length of
738          * protocol names is less than 255.
739          */
740         *p = (unsigned char)strlen( *cur );
741         memcpy( p + 1, *cur, *p );
742         p += 1 + *p;
743     }
744 
745     *olen = p - buf;
746 
747     /* List length = olen - 2 (ext_type) - 2 (ext_len) - 2 (list_len) */
748     buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF );
749     buf[5] = (unsigned char)( ( ( *olen - 6 )      ) & 0xFF );
750 
751     /* Extension length = olen - 2 (ext_type) - 2 (ext_len) */
752     buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF );
753     buf[3] = (unsigned char)( ( ( *olen - 4 )      ) & 0xFF );
754 
755     return( 0 );
756 }
757 #endif /* MBEDTLS_SSL_ALPN */
758 
759 #if defined(MBEDTLS_SSL_DTLS_SRTP)
ssl_write_use_srtp_ext(mbedtls_ssl_context * ssl,unsigned char * buf,const unsigned char * end,size_t * olen)760 static int ssl_write_use_srtp_ext( mbedtls_ssl_context *ssl,
761                                    unsigned char *buf,
762                                    const unsigned char *end,
763                                    size_t *olen )
764 {
765     unsigned char *p = buf;
766     size_t protection_profiles_index = 0, ext_len = 0;
767     uint16_t mki_len = 0, profile_value = 0;
768 
769     *olen = 0;
770 
771     if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
772         ( ssl->conf->dtls_srtp_profile_list == NULL ) ||
773         ( ssl->conf->dtls_srtp_profile_list_len == 0 ) )
774     {
775         return( 0 );
776     }
777 
778     /* RFC 5764 section 4.1.1
779      * uint8 SRTPProtectionProfile[2];
780      *
781      * struct {
782      *   SRTPProtectionProfiles SRTPProtectionProfiles;
783      *   opaque srtp_mki<0..255>;
784      * } UseSRTPData;
785      * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
786      */
787     if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED )
788     {
789         mki_len = ssl->dtls_srtp_info.mki_len;
790     }
791     /* Extension length = 2 bytes for profiles length,
792      *                    ssl->conf->dtls_srtp_profile_list_len * 2 (each profile is 2 bytes length ),
793      *                    1 byte for srtp_mki vector length and the mki_len value
794      */
795     ext_len = 2 + 2 * ( ssl->conf->dtls_srtp_profile_list_len ) + 1 + mki_len;
796 
797     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, adding use_srtp extension" ) );
798 
799     /* Check there is room in the buffer for the extension + 4 bytes
800      * - the extension tag (2 bytes)
801      * - the extension length (2 bytes)
802      */
803     MBEDTLS_SSL_CHK_BUF_PTR( p, end, ext_len + 4 );
804 
805     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP >> 8 ) & 0xFF );
806     *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_USE_SRTP      ) & 0xFF );
807 
808 
809     *p++ = (unsigned char)( ( ( ext_len & 0xFF00 ) >> 8 ) & 0xFF );
810     *p++ = (unsigned char)( ext_len & 0xFF );
811 
812     /* protection profile length: 2*(ssl->conf->dtls_srtp_profile_list_len) */
813     /* micro-optimization:
814      * the list size is limited to MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH
815      * which is lower than 127, so the upper byte of the length is always 0
816      * For the documentation, the more generic code is left in comments
817      * *p++ = (unsigned char)( ( ( 2 * ssl->conf->dtls_srtp_profile_list_len )
818      *                        >> 8 ) & 0xFF );
819      */
820     *p++ = 0;
821     *p++ = (unsigned char)( ( 2 * ssl->conf->dtls_srtp_profile_list_len )
822                             & 0xFF );
823 
824     for( protection_profiles_index=0;
825          protection_profiles_index < ssl->conf->dtls_srtp_profile_list_len;
826          protection_profiles_index++ )
827     {
828         profile_value = mbedtls_ssl_check_srtp_profile_value
829                 ( ssl->conf->dtls_srtp_profile_list[protection_profiles_index] );
830         if( profile_value != MBEDTLS_TLS_SRTP_UNSET )
831         {
832             MBEDTLS_SSL_DEBUG_MSG( 3, ( "ssl_write_use_srtp_ext, add profile: %04x",
833                                         profile_value ) );
834             *p++ = ( ( profile_value >> 8 ) & 0xFF );
835             *p++ = ( profile_value & 0xFF );
836         }
837         else
838         {
839             /*
840              * Note: we shall never arrive here as protection profiles
841              * is checked by mbedtls_ssl_conf_dtls_srtp_protection_profiles function
842              */
843             MBEDTLS_SSL_DEBUG_MSG( 3,
844                     ( "client hello, "
845                       "illegal DTLS-SRTP protection profile %d",
846                       ssl->conf->dtls_srtp_profile_list[protection_profiles_index]
847                     ) );
848             return( MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED );
849         }
850     }
851 
852     *p++ = mki_len & 0xFF;
853 
854     if( mki_len != 0 )
855     {
856         memcpy( p, ssl->dtls_srtp_info.mki_value, mki_len );
857         /*
858          * Increment p to point to the current position.
859          */
860         p += mki_len;
861         MBEDTLS_SSL_DEBUG_BUF( 3, "sending mki",  ssl->dtls_srtp_info.mki_value,
862                                ssl->dtls_srtp_info.mki_len );
863     }
864 
865     /*
866      * total extension length: extension type (2 bytes)
867      *                         + extension length (2 bytes)
868      *                         + protection profile length (2 bytes)
869      *                         + 2 * number of protection profiles
870      *                         + srtp_mki vector length(1 byte)
871      *                         + mki value
872      */
873     *olen = p - buf;
874 
875     return( 0 );
876 }
877 #endif /* MBEDTLS_SSL_DTLS_SRTP */
878 
879 /*
880  * Generate random bytes for ClientHello
881  */
ssl_generate_random(mbedtls_ssl_context * ssl)882 static int ssl_generate_random( mbedtls_ssl_context *ssl )
883 {
884     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
885     unsigned char *p = ssl->handshake->randbytes;
886 #if defined(MBEDTLS_HAVE_TIME)
887     mbedtls_time_t t;
888 #endif
889 
890     /*
891      * When responding to a verify request, MUST reuse random (RFC 6347 4.2.1)
892      */
893 #if defined(MBEDTLS_SSL_PROTO_DTLS)
894     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
895         ssl->handshake->verify_cookie != NULL )
896     {
897         return( 0 );
898     }
899 #endif
900 
901 #if defined(MBEDTLS_HAVE_TIME)
902     t = mbedtls_time( NULL );
903     *p++ = (unsigned char)( t >> 24 );
904     *p++ = (unsigned char)( t >> 16 );
905     *p++ = (unsigned char)( t >>  8 );
906     *p++ = (unsigned char)( t       );
907 
908     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, current time: %lu", t ) );
909 #else
910     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 )
911         return( ret );
912 
913     p += 4;
914 #endif /* MBEDTLS_HAVE_TIME */
915 
916     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 )
917         return( ret );
918 
919     return( 0 );
920 }
921 
922 /**
923  * \brief           Validate cipher suite against config in SSL context.
924  *
925  * \param suite_info    cipher suite to validate
926  * \param ssl           SSL context
927  * \param min_minor_ver Minimal minor version to accept a cipher suite
928  * \param max_minor_ver Maximal minor version to accept a cipher suite
929  *
930  * \return          0 if valid, else 1
931  */
ssl_validate_ciphersuite(const mbedtls_ssl_ciphersuite_t * suite_info,const mbedtls_ssl_context * ssl,int min_minor_ver,int max_minor_ver)932 static int ssl_validate_ciphersuite(
933     const mbedtls_ssl_ciphersuite_t * suite_info,
934     const mbedtls_ssl_context * ssl,
935     int min_minor_ver, int max_minor_ver )
936 {
937     (void) ssl;
938     if( suite_info == NULL )
939         return( 1 );
940 
941     if( suite_info->min_minor_ver > max_minor_ver ||
942             suite_info->max_minor_ver < min_minor_ver )
943         return( 1 );
944 
945 #if defined(MBEDTLS_SSL_PROTO_DTLS)
946     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
947             ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) )
948         return( 1 );
949 #endif
950 
951 #if defined(MBEDTLS_ARC4_C)
952     if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED &&
953             suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 )
954         return( 1 );
955 #endif
956 
957 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
958     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
959             mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 )
960         return( 1 );
961 #endif
962 
963     /* Don't suggest PSK-based ciphersuite if no PSK is available. */
964 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
965     if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) &&
966         ssl_conf_has_static_psk( ssl->conf ) == 0 )
967     {
968         return( 1 );
969     }
970 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
971 
972     return( 0 );
973 }
974 
ssl_write_client_hello(mbedtls_ssl_context * ssl)975 static int ssl_write_client_hello( mbedtls_ssl_context *ssl )
976 {
977     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
978     size_t i, n, olen, ext_len = 0;
979 
980     unsigned char *buf;
981     unsigned char *p, *q;
982     const unsigned char *end;
983 
984     unsigned char offer_compress;
985     const int *ciphersuites;
986     const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
987 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
988     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
989     int uses_ec = 0;
990 #endif
991 
992     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client hello" ) );
993 
994     if( ssl->conf->f_rng == NULL )
995     {
996         MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") );
997         return( MBEDTLS_ERR_SSL_NO_RNG );
998     }
999 
1000 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1001     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
1002 #endif
1003     {
1004         ssl->major_ver = ssl->conf->min_major_ver;
1005         ssl->minor_ver = ssl->conf->min_minor_ver;
1006     }
1007 
1008     if( ssl->conf->max_major_ver == 0 )
1009     {
1010         MBEDTLS_SSL_DEBUG_MSG( 1,
1011             ( "configured max major version is invalid, consider using mbedtls_ssl_config_defaults()" ) );
1012         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
1013     }
1014 
1015     buf = ssl->out_msg;
1016     end = buf + MBEDTLS_SSL_OUT_CONTENT_LEN;
1017 
1018     /*
1019      * Check if there's enough space for the first part of the ClientHello
1020      * consisting of the 38 bytes described below, the session identifier (at
1021      * most 32 bytes) and its length (1 byte).
1022      *
1023      * Use static upper bounds instead of the actual values
1024      * to allow the compiler to optimize this away.
1025      */
1026     MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 );
1027 
1028     /*
1029      * The 38 first bytes of the ClientHello:
1030      *     0  .   0   handshake type (written later)
1031      *     1  .   3   handshake length (written later)
1032      *     4  .   5   highest version supported
1033      *     6  .   9   current UNIX time
1034      *    10  .  37   random bytes
1035      *
1036      * The current UNIX time (4 bytes) and following 28 random bytes are written
1037      * by ssl_generate_random() into ssl->handshake->randbytes buffer and then
1038      * copied from there into the output buffer.
1039      */
1040 
1041     p = buf + 4;
1042     mbedtls_ssl_write_version( ssl->conf->max_major_ver,
1043                                ssl->conf->max_minor_ver,
1044                                ssl->conf->transport, p );
1045     p += 2;
1046 
1047     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, max version: [%d:%d]",
1048                    buf[4], buf[5] ) );
1049 
1050     if( ( ret = ssl_generate_random( ssl ) ) != 0 )
1051     {
1052         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_generate_random", ret );
1053         return( ret );
1054     }
1055 
1056     memcpy( p, ssl->handshake->randbytes, 32 );
1057     MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", p, 32 );
1058     p += 32;
1059 
1060     /*
1061      *    38  .  38   session id length
1062      *    39  . 39+n  session id
1063      *   39+n . 39+n  DTLS only: cookie length (1 byte)
1064      *   40+n .  ..   DTLS only: cookie
1065      *   ..   . ..    ciphersuitelist length (2 bytes)
1066      *   ..   . ..    ciphersuitelist
1067      *   ..   . ..    compression methods length (1 byte)
1068      *   ..   . ..    compression methods
1069      *   ..   . ..    extensions length (2 bytes)
1070      *   ..   . ..    extensions
1071      */
1072     n = ssl->session_negotiate->id_len;
1073 
1074     if( n < 16 || n > 32 ||
1075 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1076         ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
1077 #endif
1078         ssl->handshake->resume == 0 )
1079     {
1080         n = 0;
1081     }
1082 
1083 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1084     /*
1085      * RFC 5077 section 3.4: "When presenting a ticket, the client MAY
1086      * generate and include a Session ID in the TLS ClientHello."
1087      */
1088 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1089     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
1090 #endif
1091     {
1092         if( ssl->session_negotiate->ticket != NULL &&
1093                 ssl->session_negotiate->ticket_len != 0 )
1094         {
1095             ret = ssl->conf->f_rng( ssl->conf->p_rng,
1096                                     ssl->session_negotiate->id, 32 );
1097 
1098             if( ret != 0 )
1099                 return( ret );
1100 
1101             ssl->session_negotiate->id_len = n = 32;
1102         }
1103     }
1104 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1105 
1106     /*
1107      * The first check of the output buffer size above (
1108      * MBEDTLS_SSL_CHK_BUF_PTR( buf, end, 38 + 1 + 32 );)
1109      * has checked that there is enough space in the output buffer for the
1110      * session identifier length byte and the session identifier (n <= 32).
1111      */
1112     *p++ = (unsigned char) n;
1113 
1114     for( i = 0; i < n; i++ )
1115         *p++ = ssl->session_negotiate->id[i];
1116 
1117     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, session id len.: %d", n ) );
1118     MBEDTLS_SSL_DEBUG_BUF( 3,   "client hello, session id", buf + 39, n );
1119 
1120     /*
1121      *   With 'n' being the length of the session identifier
1122      *
1123      *   39+n . 39+n  DTLS only: cookie length (1 byte)
1124      *   40+n .  ..   DTLS only: cookie
1125      *   ..   . ..    ciphersuitelist length (2 bytes)
1126      *   ..   . ..    ciphersuitelist
1127      *   ..   . ..    compression methods length (1 byte)
1128      *   ..   . ..    compression methods
1129      *   ..   . ..    extensions length (2 bytes)
1130      *   ..   . ..    extensions
1131      */
1132 
1133     /*
1134      * DTLS cookie
1135      */
1136 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1137     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1138     {
1139         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 1 );
1140 
1141         if( ssl->handshake->verify_cookie == NULL )
1142         {
1143             MBEDTLS_SSL_DEBUG_MSG( 3, ( "no verify cookie to send" ) );
1144             *p++ = 0;
1145         }
1146         else
1147         {
1148             MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie",
1149                               ssl->handshake->verify_cookie,
1150                               ssl->handshake->verify_cookie_len );
1151 
1152             *p++ = ssl->handshake->verify_cookie_len;
1153 
1154             MBEDTLS_SSL_CHK_BUF_PTR( p, end,
1155                                      ssl->handshake->verify_cookie_len );
1156             memcpy( p, ssl->handshake->verify_cookie,
1157                        ssl->handshake->verify_cookie_len );
1158             p += ssl->handshake->verify_cookie_len;
1159         }
1160     }
1161 #endif
1162 
1163     /*
1164      * Ciphersuite list
1165      */
1166     ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver];
1167 
1168     /* Skip writing ciphersuite length for now */
1169     n = 0;
1170     q = p;
1171 
1172     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
1173     p += 2;
1174 
1175     for( i = 0; ciphersuites[i] != 0; i++ )
1176     {
1177         ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( ciphersuites[i] );
1178 
1179         if( ssl_validate_ciphersuite( ciphersuite_info, ssl,
1180                                       ssl->conf->min_minor_ver,
1181                                       ssl->conf->max_minor_ver ) != 0 )
1182             continue;
1183 
1184         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, add ciphersuite: %#04x (%s)",
1185                                     ciphersuites[i], ciphersuite_info->name ) );
1186 
1187 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1188     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1189         uses_ec |= mbedtls_ssl_ciphersuite_uses_ec( ciphersuite_info );
1190 #endif
1191 
1192         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
1193 
1194         n++;
1195         *p++ = (unsigned char)( ciphersuites[i] >> 8 );
1196         *p++ = (unsigned char)( ciphersuites[i]      );
1197     }
1198 
1199     MBEDTLS_SSL_DEBUG_MSG( 3,
1200         ( "client hello, got %d ciphersuites (excluding SCSVs)", n ) );
1201 
1202     /*
1203      * Add TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1204      */
1205 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1206     if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE )
1207 #endif
1208     {
1209         MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding EMPTY_RENEGOTIATION_INFO_SCSV" ) );
1210         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
1211         *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO >> 8 );
1212         *p++ = (unsigned char)( MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO      );
1213         n++;
1214     }
1215 
1216     /* Some versions of OpenSSL don't handle it correctly if not at end */
1217 #if defined(MBEDTLS_SSL_FALLBACK_SCSV)
1218     if( ssl->conf->fallback == MBEDTLS_SSL_IS_FALLBACK )
1219     {
1220         MBEDTLS_SSL_DEBUG_MSG( 3, ( "adding FALLBACK_SCSV" ) );
1221 
1222         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
1223         *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 );
1224         *p++ = (unsigned char)( MBEDTLS_SSL_FALLBACK_SCSV_VALUE      );
1225         n++;
1226     }
1227 #endif
1228 
1229     *q++ = (unsigned char)( n >> 7 );
1230     *q++ = (unsigned char)( n << 1 );
1231 
1232 #if defined(MBEDTLS_ZLIB_SUPPORT)
1233     offer_compress = 1;
1234 #else
1235     offer_compress = 0;
1236 #endif
1237 
1238     /*
1239      * We don't support compression with DTLS right now: if many records come
1240      * in the same datagram, uncompressing one could overwrite the next one.
1241      * We don't want to add complexity for handling that case unless there is
1242      * an actual need for it.
1243      */
1244 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1245     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1246         offer_compress = 0;
1247 #endif
1248 
1249     if( offer_compress )
1250     {
1251         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 2 ) );
1252         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d %d",
1253                                     MBEDTLS_SSL_COMPRESS_DEFLATE,
1254                                     MBEDTLS_SSL_COMPRESS_NULL ) );
1255 
1256         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 3 );
1257         *p++ = 2;
1258         *p++ = MBEDTLS_SSL_COMPRESS_DEFLATE;
1259         *p++ = MBEDTLS_SSL_COMPRESS_NULL;
1260     }
1261     else
1262     {
1263         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress len.: %d", 1 ) );
1264         MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, compress alg.: %d",
1265                             MBEDTLS_SSL_COMPRESS_NULL ) );
1266 
1267         MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
1268         *p++ = 1;
1269         *p++ = MBEDTLS_SSL_COMPRESS_NULL;
1270     }
1271 
1272     /* First write extensions, then the total length */
1273 
1274     MBEDTLS_SSL_CHK_BUF_PTR( p, end, 2 );
1275 
1276 #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1277     if( ( ret = ssl_write_hostname_ext( ssl, p + 2 + ext_len,
1278                                         end, &olen ) ) != 0 )
1279     {
1280         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_hostname_ext", ret );
1281         return( ret );
1282     }
1283     ext_len += olen;
1284 #endif
1285 
1286     /* Note that TLS_EMPTY_RENEGOTIATION_INFO_SCSV is always added
1287      * even if MBEDTLS_SSL_RENEGOTIATION is not defined. */
1288 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1289     if( ( ret = ssl_write_renegotiation_ext( ssl, p + 2 + ext_len,
1290                                              end, &olen ) ) != 0 )
1291     {
1292         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_renegotiation_ext", ret );
1293         return( ret );
1294     }
1295     ext_len += olen;
1296 #endif
1297 
1298 #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
1299     defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1300     if( ( ret = ssl_write_signature_algorithms_ext( ssl, p + 2 + ext_len,
1301                                                     end, &olen ) ) != 0 )
1302     {
1303         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_signature_algorithms_ext", ret );
1304         return( ret );
1305     }
1306     ext_len += olen;
1307 #endif
1308 
1309 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1310     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1311     if( uses_ec )
1312     {
1313         if( ( ret = ssl_write_supported_elliptic_curves_ext( ssl, p + 2 + ext_len,
1314                                                              end, &olen ) ) != 0 )
1315         {
1316             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_elliptic_curves_ext", ret );
1317             return( ret );
1318         }
1319         ext_len += olen;
1320 
1321         if( ( ret = ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len,
1322                                                            end, &olen ) ) != 0 )
1323         {
1324             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_supported_point_formats_ext", ret );
1325             return( ret );
1326         }
1327         ext_len += olen;
1328     }
1329 #endif
1330 
1331 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1332     if( ( ret = ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len,
1333                                             end, &olen ) ) != 0 )
1334     {
1335         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_ecjpake_kkpp_ext", ret );
1336         return( ret );
1337     }
1338     ext_len += olen;
1339 #endif
1340 
1341 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1342     if( ( ret = ssl_write_cid_ext( ssl, p + 2 + ext_len, end, &olen ) ) != 0 )
1343     {
1344         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_cid_ext", ret );
1345         return( ret );
1346     }
1347     ext_len += olen;
1348 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1349 
1350 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1351     if( ( ret = ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len,
1352                                                    end, &olen ) ) != 0 )
1353     {
1354         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_max_fragment_length_ext", ret );
1355         return( ret );
1356     }
1357     ext_len += olen;
1358 #endif
1359 
1360 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1361     if( ( ret = ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len,
1362                                               end, &olen ) ) != 0 )
1363     {
1364         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_truncated_hmac_ext", ret );
1365         return( ret );
1366     }
1367     ext_len += olen;
1368 #endif
1369 
1370 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1371     if( ( ret = ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len,
1372                                                 end, &olen ) ) != 0 )
1373     {
1374         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_encrypt_then_mac_ext", ret );
1375         return( ret );
1376     }
1377     ext_len += olen;
1378 #endif
1379 
1380 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1381     if( ( ret = ssl_write_extended_ms_ext( ssl, p + 2 + ext_len,
1382                                            end, &olen ) ) != 0 )
1383     {
1384         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_extended_ms_ext", ret );
1385         return( ret );
1386     }
1387     ext_len += olen;
1388 #endif
1389 
1390 #if defined(MBEDTLS_SSL_ALPN)
1391     if( ( ret = ssl_write_alpn_ext( ssl, p + 2 + ext_len,
1392                                     end, &olen ) ) != 0 )
1393     {
1394         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_alpn_ext", ret );
1395         return( ret );
1396     }
1397     ext_len += olen;
1398 #endif
1399 
1400 #if defined(MBEDTLS_SSL_DTLS_SRTP)
1401     if( ( ret = ssl_write_use_srtp_ext( ssl, p + 2 + ext_len,
1402                                         end, &olen ) ) != 0 )
1403     {
1404         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_use_srtp_ext", ret );
1405         return( ret );
1406     }
1407     ext_len += olen;
1408 #endif
1409 
1410 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
1411     if( ( ret = ssl_write_session_ticket_ext( ssl, p + 2 + ext_len,
1412                                               end, &olen ) ) != 0 )
1413     {
1414         MBEDTLS_SSL_DEBUG_RET( 1, "ssl_write_session_ticket_ext", ret );
1415         return( ret );
1416     }
1417     ext_len += olen;
1418 #endif
1419 
1420     /* olen unused if all extensions are disabled */
1421     ((void) olen);
1422 
1423     MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello, total extension length: %d",
1424                                 ext_len ) );
1425 
1426     if( ext_len > 0 )
1427     {
1428         /* No need to check for space here, because the extension
1429          * writing functions already took care of that. */
1430         *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF );
1431         *p++ = (unsigned char)( ( ext_len      ) & 0xFF );
1432         p += ext_len;
1433     }
1434 
1435     ssl->out_msglen  = p - buf;
1436     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
1437     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_HELLO;
1438 
1439     ssl->state++;
1440 
1441 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1442     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
1443         mbedtls_ssl_send_flight_completed( ssl );
1444 #endif
1445 
1446     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
1447     {
1448         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
1449         return( ret );
1450     }
1451 
1452 #if defined(MBEDTLS_SSL_PROTO_DTLS)
1453     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
1454         ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
1455     {
1456         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret );
1457         return( ret );
1458     }
1459 #endif /* MBEDTLS_SSL_PROTO_DTLS */
1460 
1461     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client hello" ) );
1462 
1463     return( 0 );
1464 }
1465 
ssl_parse_renegotiation_info(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1466 static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl,
1467                                          const unsigned char *buf,
1468                                          size_t len )
1469 {
1470 #if defined(MBEDTLS_SSL_RENEGOTIATION)
1471     if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE )
1472     {
1473         /* Check verify-data in constant-time. The length OTOH is no secret */
1474         if( len    != 1 + ssl->verify_data_len * 2 ||
1475             buf[0] !=     ssl->verify_data_len * 2 ||
1476             mbedtls_ssl_safer_memcmp( buf + 1,
1477                           ssl->own_verify_data, ssl->verify_data_len ) != 0 ||
1478             mbedtls_ssl_safer_memcmp( buf + 1 + ssl->verify_data_len,
1479                           ssl->peer_verify_data, ssl->verify_data_len ) != 0 )
1480         {
1481             MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) );
1482             mbedtls_ssl_send_alert_message(
1483                 ssl,
1484                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1485                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1486             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1487         }
1488     }
1489     else
1490 #endif /* MBEDTLS_SSL_RENEGOTIATION */
1491     {
1492         if( len != 1 || buf[0] != 0x00 )
1493         {
1494             MBEDTLS_SSL_DEBUG_MSG( 1,
1495                 ( "non-zero length renegotiation info" ) );
1496             mbedtls_ssl_send_alert_message(
1497                 ssl,
1498                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1499                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1500             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1501         }
1502 
1503         ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
1504     }
1505 
1506     return( 0 );
1507 }
1508 
1509 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
ssl_parse_max_fragment_length_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1510 static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl,
1511                                               const unsigned char *buf,
1512                                               size_t len )
1513 {
1514     /*
1515      * server should use the extension only if we did,
1516      * and if so the server's value should match ours (and len is always 1)
1517      */
1518     if( ssl->conf->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ||
1519         len != 1 ||
1520         buf[0] != ssl->conf->mfl_code )
1521     {
1522         MBEDTLS_SSL_DEBUG_MSG( 1,
1523             ( "non-matching max fragment length extension" ) );
1524         mbedtls_ssl_send_alert_message(
1525             ssl,
1526             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1527             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1528         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1529     }
1530 
1531     return( 0 );
1532 }
1533 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1534 
1535 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
ssl_parse_truncated_hmac_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1536 static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl,
1537                                          const unsigned char *buf,
1538                                          size_t len )
1539 {
1540     if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ||
1541         len != 0 )
1542     {
1543         MBEDTLS_SSL_DEBUG_MSG( 1,
1544             ( "non-matching truncated HMAC extension" ) );
1545         mbedtls_ssl_send_alert_message(
1546             ssl,
1547             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1548             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1549         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1550     }
1551 
1552     ((void) buf);
1553 
1554     ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED;
1555 
1556     return( 0 );
1557 }
1558 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1559 
1560 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
ssl_parse_cid_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1561 static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl,
1562                               const unsigned char *buf,
1563                               size_t len )
1564 {
1565     size_t peer_cid_len;
1566 
1567     if( /* CID extension only makes sense in DTLS */
1568         ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
1569         /* The server must only send the CID extension if we have offered it. */
1570         ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED )
1571     {
1572         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension unexpected" ) );
1573         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1574                                      MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1575         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1576     }
1577 
1578     if( len == 0 )
1579     {
1580         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) );
1581         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1582                                      MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1583         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1584     }
1585 
1586     peer_cid_len = *buf++;
1587     len--;
1588 
1589     if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX )
1590     {
1591         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) );
1592         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1593                                      MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1594         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1595     }
1596 
1597     if( len != peer_cid_len )
1598     {
1599         MBEDTLS_SSL_DEBUG_MSG( 1, ( "CID extension invalid" ) );
1600         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1601                                      MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1602         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1603     }
1604 
1605     ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
1606     ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
1607     memcpy( ssl->handshake->peer_cid, buf, peer_cid_len );
1608 
1609     MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) );
1610     MBEDTLS_SSL_DEBUG_BUF( 3, "Server CID", buf, peer_cid_len );
1611 
1612     return( 0 );
1613 }
1614 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1615 
1616 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
ssl_parse_encrypt_then_mac_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1617 static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl,
1618                                          const unsigned char *buf,
1619                                          size_t len )
1620 {
1621     if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED ||
1622         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
1623         len != 0 )
1624     {
1625         MBEDTLS_SSL_DEBUG_MSG( 1,
1626             ( "non-matching encrypt-then-MAC extension" ) );
1627         mbedtls_ssl_send_alert_message(
1628             ssl,
1629             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1630             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1631         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1632     }
1633 
1634     ((void) buf);
1635 
1636     ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
1637 
1638     return( 0 );
1639 }
1640 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1641 
1642 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
ssl_parse_extended_ms_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1643 static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl,
1644                                          const unsigned char *buf,
1645                                          size_t len )
1646 {
1647     if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED ||
1648         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
1649         len != 0 )
1650     {
1651         MBEDTLS_SSL_DEBUG_MSG( 1,
1652             ( "non-matching extended master secret extension" ) );
1653         mbedtls_ssl_send_alert_message(
1654             ssl,
1655             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1656             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1657         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1658     }
1659 
1660     ((void) buf);
1661 
1662     ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
1663 
1664     return( 0 );
1665 }
1666 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1667 
1668 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_parse_session_ticket_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1669 static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl,
1670                                          const unsigned char *buf,
1671                                          size_t len )
1672 {
1673     if( ssl->conf->session_tickets == MBEDTLS_SSL_SESSION_TICKETS_DISABLED ||
1674         len != 0 )
1675     {
1676         MBEDTLS_SSL_DEBUG_MSG( 1,
1677             ( "non-matching session ticket extension" ) );
1678         mbedtls_ssl_send_alert_message(
1679             ssl,
1680             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1681             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1682         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1683     }
1684 
1685     ((void) buf);
1686 
1687     ssl->handshake->new_session_ticket = 1;
1688 
1689     return( 0 );
1690 }
1691 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
1692 
1693 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
1694     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_parse_supported_point_formats_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1695 static int ssl_parse_supported_point_formats_ext( mbedtls_ssl_context *ssl,
1696                                                   const unsigned char *buf,
1697                                                   size_t len )
1698 {
1699     size_t list_size;
1700     const unsigned char *p;
1701 
1702     if( len == 0 || (size_t)( buf[0] + 1 ) != len )
1703     {
1704         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
1705         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1706                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1707         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1708     }
1709     list_size = buf[0];
1710 
1711     p = buf + 1;
1712     while( list_size > 0 )
1713     {
1714         if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
1715             p[0] == MBEDTLS_ECP_PF_COMPRESSED )
1716         {
1717 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C)
1718             ssl->handshake->ecdh_ctx.point_format = p[0];
1719 #endif
1720 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1721             ssl->handshake->ecjpake_ctx.point_format = p[0];
1722 #endif
1723             MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) );
1724             return( 0 );
1725         }
1726 
1727         list_size--;
1728         p++;
1729     }
1730 
1731     MBEDTLS_SSL_DEBUG_MSG( 1, ( "no point format in common" ) );
1732     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1733                                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1734     return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1735 }
1736 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
1737           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1738 
1739 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
ssl_parse_ecjpake_kkpp(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1740 static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl,
1741                                    const unsigned char *buf,
1742                                    size_t len )
1743 {
1744     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1745 
1746     if( ssl->handshake->ciphersuite_info->key_exchange !=
1747         MBEDTLS_KEY_EXCHANGE_ECJPAKE )
1748     {
1749         MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) );
1750         return( 0 );
1751     }
1752 
1753     /* If we got here, we no longer need our cached extension */
1754     mbedtls_free( ssl->handshake->ecjpake_cache );
1755     ssl->handshake->ecjpake_cache = NULL;
1756     ssl->handshake->ecjpake_cache_len = 0;
1757 
1758     if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx,
1759                                                 buf, len ) ) != 0 )
1760     {
1761         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret );
1762         mbedtls_ssl_send_alert_message(
1763             ssl,
1764             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1765             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1766         return( ret );
1767     }
1768 
1769     return( 0 );
1770 }
1771 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1772 
1773 #if defined(MBEDTLS_SSL_ALPN)
ssl_parse_alpn_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1774 static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl,
1775                                const unsigned char *buf, size_t len )
1776 {
1777     size_t list_len, name_len;
1778     const char **p;
1779 
1780     /* If we didn't send it, the server shouldn't send it */
1781     if( ssl->conf->alpn_list == NULL )
1782     {
1783         MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching ALPN extension" ) );
1784         mbedtls_ssl_send_alert_message(
1785             ssl,
1786             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1787             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1788         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1789     }
1790 
1791     /*
1792      * opaque ProtocolName<1..2^8-1>;
1793      *
1794      * struct {
1795      *     ProtocolName protocol_name_list<2..2^16-1>
1796      * } ProtocolNameList;
1797      *
1798      * the "ProtocolNameList" MUST contain exactly one "ProtocolName"
1799      */
1800 
1801     /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */
1802     if( len < 4 )
1803     {
1804         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1805                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1806         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1807     }
1808 
1809     list_len = ( buf[0] << 8 ) | buf[1];
1810     if( list_len != len - 2 )
1811     {
1812         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1813                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1814         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1815     }
1816 
1817     name_len = buf[2];
1818     if( name_len != list_len - 1 )
1819     {
1820         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1821                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1822         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1823     }
1824 
1825     /* Check that the server chosen protocol was in our list and save it */
1826     for( p = ssl->conf->alpn_list; *p != NULL; p++ )
1827     {
1828         if( name_len == strlen( *p ) &&
1829             memcmp( buf + 3, *p, name_len ) == 0 )
1830         {
1831             ssl->alpn_chosen = *p;
1832             return( 0 );
1833         }
1834     }
1835 
1836     MBEDTLS_SSL_DEBUG_MSG( 1, ( "ALPN extension: no matching protocol" ) );
1837     mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1838                                     MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1839     return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1840 }
1841 #endif /* MBEDTLS_SSL_ALPN */
1842 
1843 #if defined(MBEDTLS_SSL_DTLS_SRTP)
ssl_parse_use_srtp_ext(mbedtls_ssl_context * ssl,const unsigned char * buf,size_t len)1844 static int ssl_parse_use_srtp_ext( mbedtls_ssl_context *ssl,
1845                                    const unsigned char *buf,
1846                                    size_t len )
1847 {
1848     mbedtls_ssl_srtp_profile server_protection = MBEDTLS_TLS_SRTP_UNSET;
1849     size_t i, mki_len = 0;
1850     uint16_t server_protection_profile_value = 0;
1851 
1852     /* If use_srtp is not configured, just ignore the extension */
1853     if( ( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ||
1854         ( ssl->conf->dtls_srtp_profile_list == NULL ) ||
1855         ( ssl->conf->dtls_srtp_profile_list_len == 0 ) )
1856         return( 0 );
1857 
1858     /* RFC 5764 section 4.1.1
1859      * uint8 SRTPProtectionProfile[2];
1860      *
1861      * struct {
1862      *   SRTPProtectionProfiles SRTPProtectionProfiles;
1863      *   opaque srtp_mki<0..255>;
1864      * } UseSRTPData;
1865 
1866      * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
1867      *
1868      */
1869     if( ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED )
1870     {
1871         mki_len = ssl->dtls_srtp_info.mki_len;
1872     }
1873 
1874     /*
1875      * Length is 5 + optional mki_value : one protection profile length (2 bytes)
1876      *                                      + protection profile (2 bytes)
1877      *                                      + mki_len(1 byte)
1878      *                                      and optional srtp_mki
1879      */
1880     if( ( len < 5 ) || ( len != ( buf[4] + 5u ) ) )
1881         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1882 
1883     /*
1884      * get the server protection profile
1885      */
1886 
1887     /*
1888      * protection profile length must be 0x0002 as we must have only
1889      * one protection profile in server Hello
1890      */
1891     if( (  buf[0] != 0 ) || ( buf[1] != 2 ) )
1892         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1893 
1894     server_protection_profile_value = ( buf[2] << 8 ) | buf[3];
1895     server_protection = mbedtls_ssl_check_srtp_profile_value(
1896                     server_protection_profile_value );
1897     if( server_protection != MBEDTLS_TLS_SRTP_UNSET )
1898     {
1899         MBEDTLS_SSL_DEBUG_MSG( 3, ( "found srtp profile: %s",
1900                                       mbedtls_ssl_get_srtp_profile_as_string(
1901                                               server_protection ) ) );
1902     }
1903 
1904     ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
1905 
1906     /*
1907      * Check we have the server profile in our list
1908      */
1909     for( i=0; i < ssl->conf->dtls_srtp_profile_list_len; i++)
1910     {
1911         if( server_protection == ssl->conf->dtls_srtp_profile_list[i] )
1912         {
1913             ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
1914             MBEDTLS_SSL_DEBUG_MSG( 3, ( "selected srtp profile: %s",
1915                                       mbedtls_ssl_get_srtp_profile_as_string(
1916                                               server_protection ) ) );
1917             break;
1918         }
1919     }
1920 
1921     /* If no match was found : server problem, it shall never answer with incompatible profile */
1922     if( ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET )
1923     {
1924         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1925                                         MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
1926         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1927     }
1928 
1929     /* If server does not use mki in its reply, make sure the client won't keep
1930      * one as negotiated */
1931     if( len == 5 )
1932     {
1933         ssl->dtls_srtp_info.mki_len = 0;
1934     }
1935 
1936     /*
1937      * RFC5764:
1938      *  If the client detects a nonzero-length MKI in the server's response
1939      *  that is different than the one the client offered, then the client
1940      *  MUST abort the handshake and SHOULD send an invalid_parameter alert.
1941      */
1942     if( len > 5  && ( buf[4] != mki_len ||
1943         ( memcmp( ssl->dtls_srtp_info.mki_value, &buf[5], mki_len ) ) ) )
1944     {
1945         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1946                                         MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
1947         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1948     }
1949 #if defined (MBEDTLS_DEBUG_C)
1950     if( len > 5 )
1951     {
1952         MBEDTLS_SSL_DEBUG_BUF( 3, "received mki", ssl->dtls_srtp_info.mki_value,
1953                                                   ssl->dtls_srtp_info.mki_len );
1954     }
1955 #endif
1956     return( 0 );
1957 }
1958 #endif /* MBEDTLS_SSL_DTLS_SRTP */
1959 
1960 /*
1961  * Parse HelloVerifyRequest.  Only called after verifying the HS type.
1962  */
1963 #if defined(MBEDTLS_SSL_PROTO_DTLS)
ssl_parse_hello_verify_request(mbedtls_ssl_context * ssl)1964 static int ssl_parse_hello_verify_request( mbedtls_ssl_context *ssl )
1965 {
1966     const unsigned char *p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
1967     int major_ver, minor_ver;
1968     unsigned char cookie_len;
1969 
1970     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse hello verify request" ) );
1971 
1972     /* Check that there is enough room for:
1973      * - 2 bytes of version
1974      * - 1 byte of cookie_len
1975      */
1976     if( mbedtls_ssl_hs_hdr_len( ssl ) + 3 > ssl->in_msglen )
1977     {
1978         MBEDTLS_SSL_DEBUG_MSG( 1,
1979             ( "incoming HelloVerifyRequest message is too short" ) );
1980         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1981                                     MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
1982         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
1983     }
1984 
1985     /*
1986      * struct {
1987      *   ProtocolVersion server_version;
1988      *   opaque cookie<0..2^8-1>;
1989      * } HelloVerifyRequest;
1990      */
1991     MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 );
1992     mbedtls_ssl_read_version( &major_ver, &minor_ver, ssl->conf->transport, p );
1993     p += 2;
1994 
1995     /*
1996      * Since the RFC is not clear on this point, accept DTLS 1.0 (TLS 1.1)
1997      * even is lower than our min version.
1998      */
1999     if( major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
2000         minor_ver < MBEDTLS_SSL_MINOR_VERSION_2 ||
2001         major_ver > ssl->conf->max_major_ver  ||
2002         minor_ver > ssl->conf->max_minor_ver  )
2003     {
2004         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server version" ) );
2005 
2006         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2007                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
2008 
2009         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
2010     }
2011 
2012     cookie_len = *p++;
2013     if( ( ssl->in_msg + ssl->in_msglen ) - p < cookie_len )
2014     {
2015         MBEDTLS_SSL_DEBUG_MSG( 1,
2016             ( "cookie length does not match incoming message size" ) );
2017         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2018                                     MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2019         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2020     }
2021     MBEDTLS_SSL_DEBUG_BUF( 3, "cookie", p, cookie_len );
2022 
2023     mbedtls_free( ssl->handshake->verify_cookie );
2024 
2025     ssl->handshake->verify_cookie = mbedtls_calloc( 1, cookie_len );
2026     if( ssl->handshake->verify_cookie  == NULL )
2027     {
2028         MBEDTLS_SSL_DEBUG_MSG( 1, ( "alloc failed (%d bytes)", cookie_len ) );
2029         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
2030     }
2031 
2032     memcpy( ssl->handshake->verify_cookie, p, cookie_len );
2033     ssl->handshake->verify_cookie_len = cookie_len;
2034 
2035     /* Start over at ClientHello */
2036     ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
2037     mbedtls_ssl_reset_checksum( ssl );
2038 
2039     mbedtls_ssl_recv_flight_completed( ssl );
2040 
2041     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse hello verify request" ) );
2042 
2043     return( 0 );
2044 }
2045 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2046 
ssl_parse_server_hello(mbedtls_ssl_context * ssl)2047 static int ssl_parse_server_hello( mbedtls_ssl_context *ssl )
2048 {
2049     int ret, i;
2050     size_t n;
2051     size_t ext_len;
2052     unsigned char *buf, *ext;
2053     unsigned char comp;
2054 #if defined(MBEDTLS_ZLIB_SUPPORT)
2055     int accept_comp;
2056 #endif
2057 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2058     int renegotiation_info_seen = 0;
2059 #endif
2060     int handshake_failure = 0;
2061     const mbedtls_ssl_ciphersuite_t *suite_info;
2062 
2063     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello" ) );
2064 
2065     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
2066     {
2067         /* No alert on a read error. */
2068         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
2069         return( ret );
2070     }
2071 
2072     buf = ssl->in_msg;
2073 
2074     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
2075     {
2076 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2077         if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS )
2078         {
2079             ssl->renego_records_seen++;
2080 
2081             if( ssl->conf->renego_max_records >= 0 &&
2082                 ssl->renego_records_seen > ssl->conf->renego_max_records )
2083             {
2084                 MBEDTLS_SSL_DEBUG_MSG( 1,
2085                     ( "renegotiation requested, but not honored by server" ) );
2086                 return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2087             }
2088 
2089             MBEDTLS_SSL_DEBUG_MSG( 1,
2090                 ( "non-handshake message during renegotiation" ) );
2091 
2092             ssl->keep_current_message = 1;
2093             return( MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO );
2094         }
2095 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2096 
2097         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2098         mbedtls_ssl_send_alert_message(
2099             ssl,
2100             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2101             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
2102         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
2103     }
2104 
2105 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2106     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2107     {
2108         if( buf[0] == MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST )
2109         {
2110             MBEDTLS_SSL_DEBUG_MSG( 2, ( "received hello verify request" ) );
2111             MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
2112             return( ssl_parse_hello_verify_request( ssl ) );
2113         }
2114         else
2115         {
2116             /* We made it through the verification process */
2117             mbedtls_free( ssl->handshake->verify_cookie );
2118             ssl->handshake->verify_cookie = NULL;
2119             ssl->handshake->verify_cookie_len = 0;
2120         }
2121     }
2122 #endif /* MBEDTLS_SSL_PROTO_DTLS */
2123 
2124     if( ssl->in_hslen < 38 + mbedtls_ssl_hs_hdr_len( ssl ) ||
2125         buf[0] != MBEDTLS_SSL_HS_SERVER_HELLO )
2126     {
2127         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2128         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2129                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2130         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2131     }
2132 
2133     /*
2134      *  0   .  1    server_version
2135      *  2   . 33    random (maybe including 4 bytes of Unix time)
2136      * 34   . 34    session_id length = n
2137      * 35   . 34+n  session_id
2138      * 35+n . 36+n  cipher_suite
2139      * 37+n . 37+n  compression_method
2140      *
2141      * 38+n . 39+n  extensions length (optional)
2142      * 40+n .  ..   extensions
2143      */
2144     buf += mbedtls_ssl_hs_hdr_len( ssl );
2145 
2146     MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, version", buf + 0, 2 );
2147     mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver,
2148                       ssl->conf->transport, buf + 0 );
2149 
2150     if( ssl->major_ver < ssl->conf->min_major_ver ||
2151         ssl->minor_ver < ssl->conf->min_minor_ver ||
2152         ssl->major_ver > ssl->conf->max_major_ver ||
2153         ssl->minor_ver > ssl->conf->max_minor_ver )
2154     {
2155         MBEDTLS_SSL_DEBUG_MSG( 1,
2156             ( "server version out of bounds -  min: [%d:%d], server: [%d:%d], max: [%d:%d]",
2157               ssl->conf->min_major_ver,
2158               ssl->conf->min_minor_ver,
2159               ssl->major_ver, ssl->minor_ver,
2160               ssl->conf->max_major_ver,
2161               ssl->conf->max_minor_ver ) );
2162 
2163         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2164                                      MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION );
2165 
2166         return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION );
2167     }
2168 
2169     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu",
2170                            ( (uint32_t) buf[2] << 24 ) |
2171                            ( (uint32_t) buf[3] << 16 ) |
2172                            ( (uint32_t) buf[4] <<  8 ) |
2173                            ( (uint32_t) buf[5]       ) ) );
2174 
2175     memcpy( ssl->handshake->randbytes + 32, buf + 2, 32 );
2176 
2177     n = buf[34];
2178 
2179     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, random bytes", buf + 2, 32 );
2180 
2181     if( n > 32 )
2182     {
2183         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2184         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2185                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2186         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2187     }
2188 
2189     if( ssl->in_hslen > mbedtls_ssl_hs_hdr_len( ssl ) + 39 + n )
2190     {
2191         ext_len = ( ( buf[38 + n] <<  8 )
2192                   | ( buf[39 + n]       ) );
2193 
2194         if( ( ext_len > 0 && ext_len < 4 ) ||
2195             ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 40 + n + ext_len )
2196         {
2197             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2198             mbedtls_ssl_send_alert_message(
2199                 ssl,
2200                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2201                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2202             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2203         }
2204     }
2205     else if( ssl->in_hslen == mbedtls_ssl_hs_hdr_len( ssl ) + 38 + n )
2206     {
2207         ext_len = 0;
2208     }
2209     else
2210     {
2211         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2212         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2213                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2214         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2215     }
2216 
2217     /* ciphersuite (used later) */
2218     i = ( buf[35 + n] << 8 ) | buf[36 + n];
2219 
2220     /*
2221      * Read and check compression
2222      */
2223     comp = buf[37 + n];
2224 
2225 #if defined(MBEDTLS_ZLIB_SUPPORT)
2226     /* See comments in ssl_write_client_hello() */
2227 #if defined(MBEDTLS_SSL_PROTO_DTLS)
2228     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
2229         accept_comp = 0;
2230     else
2231 #endif
2232         accept_comp = 1;
2233 
2234     if( comp != MBEDTLS_SSL_COMPRESS_NULL &&
2235         ( comp != MBEDTLS_SSL_COMPRESS_DEFLATE || accept_comp == 0 ) )
2236 #else /* MBEDTLS_ZLIB_SUPPORT */
2237     if( comp != MBEDTLS_SSL_COMPRESS_NULL )
2238 #endif/* MBEDTLS_ZLIB_SUPPORT */
2239     {
2240         MBEDTLS_SSL_DEBUG_MSG( 1,
2241             ( "server hello, bad compression: %d", comp ) );
2242         mbedtls_ssl_send_alert_message(
2243             ssl,
2244             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2245             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2246         return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
2247     }
2248 
2249     /*
2250      * Initialize update checksum functions
2251      */
2252     ssl->handshake->ciphersuite_info = mbedtls_ssl_ciphersuite_from_id( i );
2253     if( ssl->handshake->ciphersuite_info == NULL )
2254     {
2255         MBEDTLS_SSL_DEBUG_MSG( 1,
2256             ( "ciphersuite info for %04x not found", i ) );
2257         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2258                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
2259         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
2260     }
2261 
2262     mbedtls_ssl_optimize_checksum( ssl, ssl->handshake->ciphersuite_info );
2263 
2264     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) );
2265     MBEDTLS_SSL_DEBUG_BUF( 3,   "server hello, session id", buf + 35, n );
2266 
2267     /*
2268      * Check if the session can be resumed
2269      */
2270     if( ssl->handshake->resume == 0 || n == 0 ||
2271 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2272         ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ||
2273 #endif
2274         ssl->session_negotiate->ciphersuite != i ||
2275         ssl->session_negotiate->compression != comp ||
2276         ssl->session_negotiate->id_len != n ||
2277         memcmp( ssl->session_negotiate->id, buf + 35, n ) != 0 )
2278     {
2279         ssl->state++;
2280         ssl->handshake->resume = 0;
2281 #if defined(MBEDTLS_HAVE_TIME)
2282         ssl->session_negotiate->start = mbedtls_time( NULL );
2283 #endif
2284         ssl->session_negotiate->ciphersuite = i;
2285         ssl->session_negotiate->compression = comp;
2286         ssl->session_negotiate->id_len = n;
2287         memcpy( ssl->session_negotiate->id, buf + 35, n );
2288     }
2289     else
2290     {
2291         ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
2292 
2293         if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
2294         {
2295             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
2296             mbedtls_ssl_send_alert_message(
2297                 ssl,
2298                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2299                 MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
2300             return( ret );
2301         }
2302     }
2303 
2304     MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed",
2305                    ssl->handshake->resume ? "a" : "no" ) );
2306 
2307     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %04x", i ) );
2308     MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: %d",
2309                                 buf[37 + n] ) );
2310 
2311     /*
2312      * Perform cipher suite validation in same way as in ssl_write_client_hello.
2313      */
2314     i = 0;
2315     while( 1 )
2316     {
2317         if( ssl->conf->ciphersuite_list[ssl->minor_ver][i] == 0 )
2318         {
2319             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2320             mbedtls_ssl_send_alert_message(
2321                 ssl,
2322                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2323                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2324             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2325         }
2326 
2327         if( ssl->conf->ciphersuite_list[ssl->minor_ver][i++] ==
2328             ssl->session_negotiate->ciphersuite )
2329         {
2330             break;
2331         }
2332     }
2333 
2334     suite_info = mbedtls_ssl_ciphersuite_from_id(
2335         ssl->session_negotiate->ciphersuite );
2336     if( ssl_validate_ciphersuite( suite_info, ssl, ssl->minor_ver,
2337                                   ssl->minor_ver ) != 0 )
2338     {
2339         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2340         mbedtls_ssl_send_alert_message(
2341             ssl,
2342             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2343             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2344         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2345     }
2346 
2347     MBEDTLS_SSL_DEBUG_MSG( 3,
2348         ( "server hello, chosen ciphersuite: %s", suite_info->name ) );
2349 
2350 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2351     if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA &&
2352         ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
2353     {
2354         ssl->handshake->ecrs_enabled = 1;
2355     }
2356 #endif
2357 
2358     if( comp != MBEDTLS_SSL_COMPRESS_NULL
2359 #if defined(MBEDTLS_ZLIB_SUPPORT)
2360         && comp != MBEDTLS_SSL_COMPRESS_DEFLATE
2361 #endif
2362       )
2363     {
2364         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2365         mbedtls_ssl_send_alert_message(
2366             ssl,
2367             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2368             MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
2369         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2370     }
2371     ssl->session_negotiate->compression = comp;
2372 
2373     ext = buf + 40 + n;
2374 
2375     MBEDTLS_SSL_DEBUG_MSG( 2,
2376         ( "server hello, total extension length: %d", ext_len ) );
2377 
2378     while( ext_len )
2379     {
2380         unsigned int ext_id   = ( ( ext[0] <<  8 )
2381                                 | ( ext[1]       ) );
2382         unsigned int ext_size = ( ( ext[2] <<  8 )
2383                                 | ( ext[3]       ) );
2384 
2385         if( ext_size + 4 > ext_len )
2386         {
2387             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2388             mbedtls_ssl_send_alert_message(
2389                 ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2390                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
2391             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2392         }
2393 
2394         switch( ext_id )
2395         {
2396         case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
2397             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) );
2398 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2399             renegotiation_info_seen = 1;
2400 #endif
2401 
2402             if( ( ret = ssl_parse_renegotiation_info( ssl, ext + 4,
2403                                                       ext_size ) ) != 0 )
2404                 return( ret );
2405 
2406             break;
2407 
2408 #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2409         case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
2410             MBEDTLS_SSL_DEBUG_MSG( 3,
2411                 ( "found max_fragment_length extension" ) );
2412 
2413             if( ( ret = ssl_parse_max_fragment_length_ext( ssl,
2414                             ext + 4, ext_size ) ) != 0 )
2415             {
2416                 return( ret );
2417             }
2418 
2419             break;
2420 #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
2421 
2422 #if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
2423         case MBEDTLS_TLS_EXT_TRUNCATED_HMAC:
2424             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated_hmac extension" ) );
2425 
2426             if( ( ret = ssl_parse_truncated_hmac_ext( ssl,
2427                             ext + 4, ext_size ) ) != 0 )
2428             {
2429                 return( ret );
2430             }
2431 
2432             break;
2433 #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
2434 
2435 #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2436         case MBEDTLS_TLS_EXT_CID:
2437             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) );
2438 
2439             if( ( ret = ssl_parse_cid_ext( ssl,
2440                                            ext + 4,
2441                                            ext_size ) ) != 0 )
2442             {
2443                 return( ret );
2444             }
2445 
2446             break;
2447 #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
2448 
2449 #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
2450         case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
2451             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt_then_mac extension" ) );
2452 
2453             if( ( ret = ssl_parse_encrypt_then_mac_ext( ssl,
2454                             ext + 4, ext_size ) ) != 0 )
2455             {
2456                 return( ret );
2457             }
2458 
2459             break;
2460 #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
2461 
2462 #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2463         case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
2464             MBEDTLS_SSL_DEBUG_MSG( 3,
2465                 ( "found extended_master_secret extension" ) );
2466 
2467             if( ( ret = ssl_parse_extended_ms_ext( ssl,
2468                             ext + 4, ext_size ) ) != 0 )
2469             {
2470                 return( ret );
2471             }
2472 
2473             break;
2474 #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
2475 
2476 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
2477         case MBEDTLS_TLS_EXT_SESSION_TICKET:
2478             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session_ticket extension" ) );
2479 
2480             if( ( ret = ssl_parse_session_ticket_ext( ssl,
2481                             ext + 4, ext_size ) ) != 0 )
2482             {
2483                 return( ret );
2484             }
2485 
2486             break;
2487 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
2488 
2489 #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
2490     defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2491         case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
2492             MBEDTLS_SSL_DEBUG_MSG( 3,
2493                 ( "found supported_point_formats extension" ) );
2494 
2495             if( ( ret = ssl_parse_supported_point_formats_ext( ssl,
2496                             ext + 4, ext_size ) ) != 0 )
2497             {
2498                 return( ret );
2499             }
2500 
2501             break;
2502 #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C ||
2503           MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2504 
2505 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2506         case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
2507             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake_kkpp extension" ) );
2508 
2509             if( ( ret = ssl_parse_ecjpake_kkpp( ssl,
2510                             ext + 4, ext_size ) ) != 0 )
2511             {
2512                 return( ret );
2513             }
2514 
2515             break;
2516 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2517 
2518 #if defined(MBEDTLS_SSL_ALPN)
2519         case MBEDTLS_TLS_EXT_ALPN:
2520             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) );
2521 
2522             if( ( ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ) ) != 0 )
2523                 return( ret );
2524 
2525             break;
2526 #endif /* MBEDTLS_SSL_ALPN */
2527 
2528 #if defined(MBEDTLS_SSL_DTLS_SRTP)
2529         case MBEDTLS_TLS_EXT_USE_SRTP:
2530             MBEDTLS_SSL_DEBUG_MSG( 3, ( "found use_srtp extension" ) );
2531 
2532             if( ( ret = ssl_parse_use_srtp_ext( ssl, ext + 4, ext_size ) ) != 0 )
2533                 return( ret );
2534 
2535             break;
2536 #endif /* MBEDTLS_SSL_DTLS_SRTP */
2537 
2538         default:
2539             MBEDTLS_SSL_DEBUG_MSG( 3,
2540                 ( "unknown extension found: %d (ignoring)", ext_id ) );
2541         }
2542 
2543         ext_len -= 4 + ext_size;
2544         ext += 4 + ext_size;
2545 
2546         if( ext_len > 0 && ext_len < 4 )
2547         {
2548             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello message" ) );
2549             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2550         }
2551     }
2552 
2553     /*
2554      * Renegotiation security checks
2555      */
2556     if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
2557         ssl->conf->allow_legacy_renegotiation ==
2558         MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE )
2559     {
2560         MBEDTLS_SSL_DEBUG_MSG( 1,
2561             ( "legacy renegotiation, breaking off handshake" ) );
2562         handshake_failure = 1;
2563     }
2564 #if defined(MBEDTLS_SSL_RENEGOTIATION)
2565     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2566              ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
2567              renegotiation_info_seen == 0 )
2568     {
2569         MBEDTLS_SSL_DEBUG_MSG( 1,
2570             ( "renegotiation_info extension missing (secure)" ) );
2571         handshake_failure = 1;
2572     }
2573     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2574              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
2575              ssl->conf->allow_legacy_renegotiation ==
2576              MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION )
2577     {
2578         MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) );
2579         handshake_failure = 1;
2580     }
2581     else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
2582              ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
2583              renegotiation_info_seen == 1 )
2584     {
2585         MBEDTLS_SSL_DEBUG_MSG( 1,
2586             ( "renegotiation_info extension present (legacy)" ) );
2587         handshake_failure = 1;
2588     }
2589 #endif /* MBEDTLS_SSL_RENEGOTIATION */
2590 
2591     if( handshake_failure == 1 )
2592     {
2593         mbedtls_ssl_send_alert_message(
2594             ssl,
2595             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2596             MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
2597         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO );
2598     }
2599 
2600     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello" ) );
2601 
2602     return( 0 );
2603 }
2604 
2605 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2606     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
ssl_parse_server_dh_params(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)2607 static int ssl_parse_server_dh_params( mbedtls_ssl_context *ssl,
2608                                        unsigned char **p,
2609                                        unsigned char *end )
2610 {
2611     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2612 
2613     /*
2614      * Ephemeral DH parameters:
2615      *
2616      * struct {
2617      *     opaque dh_p<1..2^16-1>;
2618      *     opaque dh_g<1..2^16-1>;
2619      *     opaque dh_Ys<1..2^16-1>;
2620      * } ServerDHParams;
2621      */
2622     if( ( ret = mbedtls_dhm_read_params( &ssl->handshake->dhm_ctx,
2623                                          p, end ) ) != 0 )
2624     {
2625         MBEDTLS_SSL_DEBUG_RET( 2, ( "mbedtls_dhm_read_params" ), ret );
2626         return( ret );
2627     }
2628 
2629     if( ssl->handshake->dhm_ctx.len * 8 < ssl->conf->dhm_min_bitlen )
2630     {
2631         MBEDTLS_SSL_DEBUG_MSG( 1, ( "DHM prime too short: %d < %d",
2632                                     ssl->handshake->dhm_ctx.len * 8,
2633                                     ssl->conf->dhm_min_bitlen ) );
2634         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2635     }
2636 
2637     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P  );
2638     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G  );
2639     MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY );
2640 
2641     return( ret );
2642 }
2643 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2644           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2645 
2646 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2647     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2648     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
2649     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
2650     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
ssl_check_server_ecdh_params(const mbedtls_ssl_context * ssl)2651 static int ssl_check_server_ecdh_params( const mbedtls_ssl_context *ssl )
2652 {
2653     const mbedtls_ecp_curve_info *curve_info;
2654     mbedtls_ecp_group_id grp_id;
2655 #if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
2656     grp_id = ssl->handshake->ecdh_ctx.grp.id;
2657 #else
2658     grp_id = ssl->handshake->ecdh_ctx.grp_id;
2659 #endif
2660 
2661     curve_info = mbedtls_ecp_curve_info_from_grp_id( grp_id );
2662     if( curve_info == NULL )
2663     {
2664         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2665         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2666     }
2667 
2668     MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDH curve: %s", curve_info->name ) );
2669 
2670 #if defined(MBEDTLS_ECP_C)
2671     if( mbedtls_ssl_check_curve( ssl, grp_id ) != 0 )
2672 #else
2673     if( ssl->handshake->ecdh_ctx.grp.nbits < 163 ||
2674         ssl->handshake->ecdh_ctx.grp.nbits > 521 )
2675 #endif
2676         return( -1 );
2677 
2678     MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
2679                             MBEDTLS_DEBUG_ECDH_QP );
2680 
2681     return( 0 );
2682 }
2683 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2684           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2685           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
2686           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
2687           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2688 
2689 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
2690         ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
2691           defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) )
ssl_parse_server_ecdh_params_psa(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)2692 static int ssl_parse_server_ecdh_params_psa( mbedtls_ssl_context *ssl,
2693                                              unsigned char **p,
2694                                              unsigned char *end )
2695 {
2696     uint16_t tls_id;
2697     size_t ecdh_bits = 0;
2698     uint8_t ecpoint_len;
2699     mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2700 
2701     /*
2702      * Parse ECC group
2703      */
2704 
2705     if( end - *p < 4 )
2706         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2707 
2708     /* First byte is curve_type; only named_curve is handled */
2709     if( *(*p)++ != MBEDTLS_ECP_TLS_NAMED_CURVE )
2710         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2711 
2712     /* Next two bytes are the namedcurve value */
2713     tls_id = *(*p)++;
2714     tls_id <<= 8;
2715     tls_id |= *(*p)++;
2716 
2717     /* Convert EC group to PSA key type. */
2718     if( ( handshake->ecdh_psa_type =
2719           mbedtls_psa_parse_tls_ecc_group( tls_id, &ecdh_bits ) ) == 0 )
2720     {
2721         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2722     }
2723     if( ecdh_bits > 0xffff )
2724         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2725     handshake->ecdh_bits = (uint16_t) ecdh_bits;
2726 
2727     /*
2728      * Put peer's ECDH public key in the format understood by PSA.
2729      */
2730 
2731     ecpoint_len = *(*p)++;
2732     if( (size_t)( end - *p ) < ecpoint_len )
2733         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2734 
2735     if( mbedtls_psa_tls_ecpoint_to_psa_ec(
2736                                     *p, ecpoint_len,
2737                                     handshake->ecdh_psa_peerkey,
2738                                     sizeof( handshake->ecdh_psa_peerkey ),
2739                                     &handshake->ecdh_psa_peerkey_len ) != 0 )
2740     {
2741         return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
2742     }
2743 
2744     *p += ecpoint_len;
2745     return( 0 );
2746 }
2747 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
2748             ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2749               MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */
2750 
2751 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2752     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
2753     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
ssl_parse_server_ecdh_params(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)2754 static int ssl_parse_server_ecdh_params( mbedtls_ssl_context *ssl,
2755                                          unsigned char **p,
2756                                          unsigned char *end )
2757 {
2758     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2759 
2760     /*
2761      * Ephemeral ECDH parameters:
2762      *
2763      * struct {
2764      *     ECParameters curve_params;
2765      *     ECPoint      public;
2766      * } ServerECDHParams;
2767      */
2768     if( ( ret = mbedtls_ecdh_read_params( &ssl->handshake->ecdh_ctx,
2769                                   (const unsigned char **) p, end ) ) != 0 )
2770     {
2771         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_read_params" ), ret );
2772 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2773         if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
2774             ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
2775 #endif
2776         return( ret );
2777     }
2778 
2779     if( ssl_check_server_ecdh_params( ssl ) != 0 )
2780     {
2781         MBEDTLS_SSL_DEBUG_MSG( 1,
2782             ( "bad server key exchange message (ECDHE curve)" ) );
2783         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2784     }
2785 
2786     return( ret );
2787 }
2788 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2789           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
2790           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
2791 
2792 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
ssl_parse_server_psk_hint(mbedtls_ssl_context * ssl,unsigned char ** p,unsigned char * end)2793 static int ssl_parse_server_psk_hint( mbedtls_ssl_context *ssl,
2794                                       unsigned char **p,
2795                                       unsigned char *end )
2796 {
2797     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2798     uint16_t  len;
2799     ((void) ssl);
2800 
2801     /*
2802      * PSK parameters:
2803      *
2804      * opaque psk_identity_hint<0..2^16-1>;
2805      */
2806     if( end - (*p) < 2 )
2807     {
2808         MBEDTLS_SSL_DEBUG_MSG( 1,
2809             ( "bad server key exchange message (psk_identity_hint length)" ) );
2810         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2811     }
2812     len = (*p)[0] << 8 | (*p)[1];
2813     *p += 2;
2814 
2815     if( end - (*p) < len )
2816     {
2817         MBEDTLS_SSL_DEBUG_MSG( 1,
2818             ( "bad server key exchange message (psk_identity_hint length)" ) );
2819         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2820     }
2821 
2822     /*
2823      * Note: we currently ignore the PKS identity hint, as we only allow one
2824      * PSK to be provisionned on the client. This could be changed later if
2825      * someone needs that feature.
2826      */
2827     *p += len;
2828     ret = 0;
2829 
2830     return( ret );
2831 }
2832 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
2833 
2834 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
2835     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
2836 /*
2837  * Generate a pre-master secret and encrypt it with the server's RSA key
2838  */
ssl_write_encrypted_pms(mbedtls_ssl_context * ssl,size_t offset,size_t * olen,size_t pms_offset)2839 static int ssl_write_encrypted_pms( mbedtls_ssl_context *ssl,
2840                                     size_t offset, size_t *olen,
2841                                     size_t pms_offset )
2842 {
2843     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2844     size_t len_bytes = ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ? 0 : 2;
2845     unsigned char *p = ssl->handshake->premaster + pms_offset;
2846     mbedtls_pk_context * peer_pk;
2847 
2848     if( offset + len_bytes > MBEDTLS_SSL_OUT_CONTENT_LEN )
2849     {
2850         MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small for encrypted pms" ) );
2851         return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
2852     }
2853 
2854     /*
2855      * Generate (part of) the pre-master as
2856      *  struct {
2857      *      ProtocolVersion client_version;
2858      *      opaque random[46];
2859      *  } PreMasterSecret;
2860      */
2861     mbedtls_ssl_write_version( ssl->conf->max_major_ver,
2862                                ssl->conf->max_minor_ver,
2863                                ssl->conf->transport, p );
2864 
2865     if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p + 2, 46 ) ) != 0 )
2866     {
2867         MBEDTLS_SSL_DEBUG_RET( 1, "f_rng", ret );
2868         return( ret );
2869     }
2870 
2871     ssl->handshake->pmslen = 48;
2872 
2873 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2874     peer_pk = &ssl->handshake->peer_pubkey;
2875 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2876     if( ssl->session_negotiate->peer_cert == NULL )
2877     {
2878         /* Should never happen */
2879         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
2880         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
2881     }
2882     peer_pk = &ssl->session_negotiate->peer_cert->pk;
2883 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2884 
2885     /*
2886      * Now write it out, encrypted
2887      */
2888     if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_RSA ) )
2889     {
2890         MBEDTLS_SSL_DEBUG_MSG( 1, ( "certificate key type mismatch" ) );
2891         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
2892     }
2893 
2894     if( ( ret = mbedtls_pk_encrypt( peer_pk,
2895                             p, ssl->handshake->pmslen,
2896                             ssl->out_msg + offset + len_bytes, olen,
2897                             MBEDTLS_SSL_OUT_CONTENT_LEN - offset - len_bytes,
2898                             ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
2899     {
2900         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_rsa_pkcs1_encrypt", ret );
2901         return( ret );
2902     }
2903 
2904 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2905     defined(MBEDTLS_SSL_PROTO_TLS1_2)
2906     if( len_bytes == 2 )
2907     {
2908         ssl->out_msg[offset+0] = (unsigned char)( *olen >> 8 );
2909         ssl->out_msg[offset+1] = (unsigned char)( *olen      );
2910         *olen += 2;
2911     }
2912 #endif
2913 
2914 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2915     /* We don't need the peer's public key anymore. Free it. */
2916     mbedtls_pk_free( peer_pk );
2917 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2918     return( 0 );
2919 }
2920 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
2921           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
2922 
2923 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2924 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
2925     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
2926     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)2927 static int ssl_parse_signature_algorithm( mbedtls_ssl_context *ssl,
2928                                           unsigned char **p,
2929                                           unsigned char *end,
2930                                           mbedtls_md_type_t *md_alg,
2931                                           mbedtls_pk_type_t *pk_alg )
2932 {
2933     ((void) ssl);
2934     *md_alg = MBEDTLS_MD_NONE;
2935     *pk_alg = MBEDTLS_PK_NONE;
2936 
2937     /* Only in TLS 1.2 */
2938     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
2939     {
2940         return( 0 );
2941     }
2942 
2943     if( (*p) + 2 > end )
2944         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2945 
2946     /*
2947      * Get hash algorithm
2948      */
2949     if( ( *md_alg = mbedtls_ssl_md_alg_from_hash( (*p)[0] ) )
2950         == MBEDTLS_MD_NONE )
2951     {
2952         MBEDTLS_SSL_DEBUG_MSG( 1,
2953             ( "Server used unsupported HashAlgorithm %d", *(p)[0] ) );
2954         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2955     }
2956 
2957     /*
2958      * Get signature algorithm
2959      */
2960     if( ( *pk_alg = mbedtls_ssl_pk_alg_from_sig( (*p)[1] ) )
2961         == MBEDTLS_PK_NONE )
2962     {
2963         MBEDTLS_SSL_DEBUG_MSG( 1,
2964             ( "server used unsupported SignatureAlgorithm %d", (*p)[1] ) );
2965         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2966     }
2967 
2968     /*
2969      * Check if the hash is acceptable
2970      */
2971     if( mbedtls_ssl_check_sig_hash( ssl, *md_alg ) != 0 )
2972     {
2973         MBEDTLS_SSL_DEBUG_MSG( 1,
2974             ( "server used HashAlgorithm %d that was not offered", *(p)[0] ) );
2975         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
2976     }
2977 
2978     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used SignatureAlgorithm %d",
2979                                 (*p)[1] ) );
2980     MBEDTLS_SSL_DEBUG_MSG( 2, ( "Server used HashAlgorithm %d",
2981                                 (*p)[0] ) );
2982     *p += 2;
2983 
2984     return( 0 );
2985 }
2986 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
2987           MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
2988           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
2989 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2990 
2991 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2992     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
ssl_get_ecdh_params_from_cert(mbedtls_ssl_context * ssl)2993 static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl )
2994 {
2995     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2996     const mbedtls_ecp_keypair *peer_key;
2997     mbedtls_pk_context * peer_pk;
2998 
2999 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3000     peer_pk = &ssl->handshake->peer_pubkey;
3001 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
3002     if( ssl->session_negotiate->peer_cert == NULL )
3003     {
3004         /* Should never happen */
3005         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3006         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3007     }
3008     peer_pk = &ssl->session_negotiate->peer_cert->pk;
3009 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
3010 
3011     if( ! mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECKEY ) )
3012     {
3013         MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) );
3014         return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
3015     }
3016 
3017     peer_key = mbedtls_pk_ec( *peer_pk );
3018 
3019     if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, peer_key,
3020                                  MBEDTLS_ECDH_THEIRS ) ) != 0 )
3021     {
3022         MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret );
3023         return( ret );
3024     }
3025 
3026     if( ssl_check_server_ecdh_params( ssl ) != 0 )
3027     {
3028         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server certificate (ECDH curve)" ) );
3029         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE );
3030     }
3031 
3032 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3033     /* We don't need the peer's public key anymore. Free it,
3034      * so that more RAM is available for upcoming expensive
3035      * operations like ECDHE. */
3036     mbedtls_pk_free( peer_pk );
3037 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
3038 
3039     return( ret );
3040 }
3041 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
3042           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3043 
ssl_parse_server_key_exchange(mbedtls_ssl_context * ssl)3044 static int ssl_parse_server_key_exchange( mbedtls_ssl_context *ssl )
3045 {
3046     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3047     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3048         ssl->handshake->ciphersuite_info;
3049     unsigned char *p = NULL, *end = NULL;
3050 
3051     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server key exchange" ) );
3052 
3053 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
3054     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
3055     {
3056         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
3057         ssl->state++;
3058         return( 0 );
3059     }
3060     ((void) p);
3061     ((void) end);
3062 #endif
3063 
3064 #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
3065     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
3066     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
3067         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
3068     {
3069         if( ( ret = ssl_get_ecdh_params_from_cert( ssl ) ) != 0 )
3070         {
3071             MBEDTLS_SSL_DEBUG_RET( 1, "ssl_get_ecdh_params_from_cert", ret );
3072             mbedtls_ssl_send_alert_message(
3073                 ssl,
3074                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3075                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
3076             return( ret );
3077         }
3078 
3079         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse server key exchange" ) );
3080         ssl->state++;
3081         return( 0 );
3082     }
3083     ((void) p);
3084     ((void) end);
3085 #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
3086           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3087 
3088 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3089     if( ssl->handshake->ecrs_enabled &&
3090         ssl->handshake->ecrs_state == ssl_ecrs_ske_start_processing )
3091     {
3092         goto start_processing;
3093     }
3094 #endif
3095 
3096     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
3097     {
3098         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
3099         return( ret );
3100     }
3101 
3102     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
3103     {
3104         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3105         mbedtls_ssl_send_alert_message(
3106             ssl,
3107             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3108             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
3109         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3110     }
3111 
3112     /*
3113      * ServerKeyExchange may be skipped with PSK and RSA-PSK when the server
3114      * doesn't use a psk_identity_hint
3115      */
3116     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE )
3117     {
3118         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
3119             ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
3120         {
3121             /* Current message is probably either
3122              * CertificateRequest or ServerHelloDone */
3123             ssl->keep_current_message = 1;
3124             goto exit;
3125         }
3126 
3127         MBEDTLS_SSL_DEBUG_MSG( 1,
3128             ( "server key exchange message must not be skipped" ) );
3129         mbedtls_ssl_send_alert_message(
3130             ssl,
3131             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3132             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
3133 
3134         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3135     }
3136 
3137 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3138     if( ssl->handshake->ecrs_enabled )
3139         ssl->handshake->ecrs_state = ssl_ecrs_ske_start_processing;
3140 
3141 start_processing:
3142 #endif
3143     p   = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
3144     end = ssl->in_msg + ssl->in_hslen;
3145     MBEDTLS_SSL_DEBUG_BUF( 3,   "server key exchange", p, end - p );
3146 
3147 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
3148     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
3149         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3150         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
3151         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
3152     {
3153         if( ssl_parse_server_psk_hint( ssl, &p, end ) != 0 )
3154         {
3155             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3156             mbedtls_ssl_send_alert_message(
3157                 ssl,
3158                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3159                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
3160             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3161         }
3162     } /* FALLTROUGH */
3163 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
3164 
3165 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) ||                       \
3166     defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3167     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ||
3168         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
3169         ; /* nothing more to do */
3170     else
3171 #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED ||
3172           MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
3173 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
3174     defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3175     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ||
3176         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
3177     {
3178         if( ssl_parse_server_dh_params( ssl, &p, end ) != 0 )
3179         {
3180             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3181             mbedtls_ssl_send_alert_message(
3182                 ssl,
3183                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3184                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
3185             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3186         }
3187     }
3188     else
3189 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
3190           MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3191 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
3192         ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
3193           defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) )
3194     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3195         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
3196     {
3197         if( ssl_parse_server_ecdh_params_psa( ssl, &p, end ) != 0 )
3198         {
3199             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3200             mbedtls_ssl_send_alert_message(
3201                 ssl,
3202                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3203                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
3204             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3205         }
3206     }
3207     else
3208 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
3209             ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3210               MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */
3211 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
3212     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) ||                     \
3213     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
3214     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3215         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ||
3216         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
3217     {
3218         if( ssl_parse_server_ecdh_params( ssl, &p, end ) != 0 )
3219         {
3220             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3221             mbedtls_ssl_send_alert_message(
3222                 ssl,
3223                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3224                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
3225             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3226         }
3227     }
3228     else
3229 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3230           MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED ||
3231           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED */
3232 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3233     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
3234     {
3235         ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx,
3236                                               p, end - p );
3237         if( ret != 0 )
3238         {
3239             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret );
3240             mbedtls_ssl_send_alert_message(
3241                 ssl,
3242                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3243                 MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
3244             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3245         }
3246     }
3247     else
3248 #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
3249     {
3250         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3251         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3252     }
3253 
3254 #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3255     if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) )
3256     {
3257         size_t sig_len, hashlen;
3258         unsigned char hash[64];
3259         mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
3260         mbedtls_pk_type_t pk_alg = MBEDTLS_PK_NONE;
3261         unsigned char *params = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
3262         size_t params_len = p - params;
3263         void *rs_ctx = NULL;
3264 
3265         mbedtls_pk_context * peer_pk;
3266 
3267         /*
3268          * Handle the digitally-signed structure
3269          */
3270 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3271         if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
3272         {
3273             if( ssl_parse_signature_algorithm( ssl, &p, end,
3274                                                &md_alg, &pk_alg ) != 0 )
3275             {
3276                 MBEDTLS_SSL_DEBUG_MSG( 1,
3277                     ( "bad server key exchange message" ) );
3278                 mbedtls_ssl_send_alert_message(
3279                     ssl,
3280                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3281                     MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
3282                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3283             }
3284 
3285             if( pk_alg !=
3286                 mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ) )
3287             {
3288                 MBEDTLS_SSL_DEBUG_MSG( 1,
3289                     ( "bad server key exchange message" ) );
3290                 mbedtls_ssl_send_alert_message(
3291                     ssl,
3292                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3293                     MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER );
3294                 return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3295             }
3296         }
3297         else
3298 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3299 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3300     defined(MBEDTLS_SSL_PROTO_TLS1_1)
3301         if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 )
3302         {
3303             pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info );
3304 
3305             /* Default hash for ECDSA is SHA-1 */
3306             if( pk_alg == MBEDTLS_PK_ECDSA && md_alg == MBEDTLS_MD_NONE )
3307                 md_alg = MBEDTLS_MD_SHA1;
3308         }
3309         else
3310 #endif
3311         {
3312             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3313             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3314         }
3315 
3316         /*
3317          * Read signature
3318          */
3319 
3320         if( p > end - 2 )
3321         {
3322             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3323             mbedtls_ssl_send_alert_message(
3324                 ssl,
3325                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3326                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3327             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3328         }
3329         sig_len = ( p[0] << 8 ) | p[1];
3330         p += 2;
3331 
3332         if( p != end - sig_len )
3333         {
3334             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3335             mbedtls_ssl_send_alert_message(
3336                 ssl,
3337                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3338                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3339             return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE );
3340         }
3341 
3342         MBEDTLS_SSL_DEBUG_BUF( 3, "signature", p, sig_len );
3343 
3344         /*
3345          * Compute the hash that has been signed
3346          */
3347 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3348     defined(MBEDTLS_SSL_PROTO_TLS1_1)
3349         if( md_alg == MBEDTLS_MD_NONE )
3350         {
3351             hashlen = 36;
3352             ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, params,
3353                                                            params_len );
3354             if( ret != 0 )
3355                 return( ret );
3356         }
3357         else
3358 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
3359           MBEDTLS_SSL_PROTO_TLS1_1 */
3360 #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
3361     defined(MBEDTLS_SSL_PROTO_TLS1_2)
3362         if( md_alg != MBEDTLS_MD_NONE )
3363         {
3364             ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen,
3365                                                           params, params_len,
3366                                                           md_alg );
3367             if( ret != 0 )
3368                 return( ret );
3369         }
3370         else
3371 #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
3372           MBEDTLS_SSL_PROTO_TLS1_2 */
3373         {
3374             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3375             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3376         }
3377 
3378         MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen );
3379 
3380 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3381         peer_pk = &ssl->handshake->peer_pubkey;
3382 #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
3383         if( ssl->session_negotiate->peer_cert == NULL )
3384         {
3385             /* Should never happen */
3386             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3387             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3388         }
3389         peer_pk = &ssl->session_negotiate->peer_cert->pk;
3390 #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
3391 
3392         /*
3393          * Verify signature
3394          */
3395         if( !mbedtls_pk_can_do( peer_pk, pk_alg ) )
3396         {
3397             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server key exchange message" ) );
3398             mbedtls_ssl_send_alert_message(
3399                 ssl,
3400                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3401                 MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE );
3402             return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH );
3403         }
3404 
3405 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3406         if( ssl->handshake->ecrs_enabled )
3407             rs_ctx = &ssl->handshake->ecrs_ctx.pk;
3408 #endif
3409 
3410         if( ( ret = mbedtls_pk_verify_restartable( peer_pk,
3411                         md_alg, hash, hashlen, p, sig_len, rs_ctx ) ) != 0 )
3412         {
3413 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3414             if( ret != MBEDTLS_ERR_ECP_IN_PROGRESS )
3415 #endif
3416                 mbedtls_ssl_send_alert_message(
3417                     ssl,
3418                     MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3419                     MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR );
3420             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret );
3421 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3422             if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
3423                 ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
3424 #endif
3425             return( ret );
3426         }
3427 
3428 #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3429         /* We don't need the peer's public key anymore. Free it,
3430          * so that more RAM is available for upcoming expensive
3431          * operations like ECDHE. */
3432         mbedtls_pk_free( peer_pk );
3433 #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
3434     }
3435 #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3436 
3437 exit:
3438     ssl->state++;
3439 
3440     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server key exchange" ) );
3441 
3442     return( 0 );
3443 }
3444 
3445 #if ! defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
ssl_parse_certificate_request(mbedtls_ssl_context * ssl)3446 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
3447 {
3448     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3449         ssl->handshake->ciphersuite_info;
3450 
3451     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
3452 
3453     if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
3454     {
3455         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
3456         ssl->state++;
3457         return( 0 );
3458     }
3459 
3460     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
3461     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3462 }
3463 #else /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
ssl_parse_certificate_request(mbedtls_ssl_context * ssl)3464 static int ssl_parse_certificate_request( mbedtls_ssl_context *ssl )
3465 {
3466     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3467     unsigned char *buf;
3468     size_t n = 0;
3469     size_t cert_type_len = 0, dn_len = 0;
3470     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3471         ssl->handshake->ciphersuite_info;
3472 
3473     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate request" ) );
3474 
3475     if( ! mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
3476     {
3477         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate request" ) );
3478         ssl->state++;
3479         return( 0 );
3480     }
3481 
3482     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
3483     {
3484         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
3485         return( ret );
3486     }
3487 
3488     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
3489     {
3490         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
3491         mbedtls_ssl_send_alert_message(
3492             ssl,
3493             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3494             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
3495         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3496     }
3497 
3498     ssl->state++;
3499     ssl->client_auth = ( ssl->in_msg[0] == MBEDTLS_SSL_HS_CERTIFICATE_REQUEST );
3500 
3501     MBEDTLS_SSL_DEBUG_MSG( 3, ( "got %s certificate request",
3502                         ssl->client_auth ? "a" : "no" ) );
3503 
3504     if( ssl->client_auth == 0 )
3505     {
3506         /* Current message is probably the ServerHelloDone */
3507         ssl->keep_current_message = 1;
3508         goto exit;
3509     }
3510 
3511     /*
3512      *  struct {
3513      *      ClientCertificateType certificate_types<1..2^8-1>;
3514      *      SignatureAndHashAlgorithm
3515      *        supported_signature_algorithms<2^16-1>; -- TLS 1.2 only
3516      *      DistinguishedName certificate_authorities<0..2^16-1>;
3517      *  } CertificateRequest;
3518      *
3519      *  Since we only support a single certificate on clients, let's just
3520      *  ignore all the information that's supposed to help us pick a
3521      *  certificate.
3522      *
3523      *  We could check that our certificate matches the request, and bail out
3524      *  if it doesn't, but it's simpler to just send the certificate anyway,
3525      *  and give the server the opportunity to decide if it should terminate
3526      *  the connection when it doesn't like our certificate.
3527      *
3528      *  Same goes for the hash in TLS 1.2's signature_algorithms: at this
3529      *  point we only have one hash available (see comments in
3530      *  write_certificate_verify), so let's just use what we have.
3531      *
3532      *  However, we still minimally parse the message to check it is at least
3533      *  superficially sane.
3534      */
3535     buf = ssl->in_msg;
3536 
3537     /* certificate_types */
3538     if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) )
3539     {
3540         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
3541         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3542                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3543         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
3544     }
3545     cert_type_len = buf[mbedtls_ssl_hs_hdr_len( ssl )];
3546     n = cert_type_len;
3547 
3548     /*
3549      * In the subsequent code there are two paths that read from buf:
3550      *     * the length of the signature algorithms field (if minor version of
3551      *       SSL is 3),
3552      *     * distinguished name length otherwise.
3553      * Both reach at most the index:
3554      *    ...hdr_len + 2 + n,
3555      * therefore the buffer length at this point must be greater than that
3556      * regardless of the actual code path.
3557      */
3558     if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n )
3559     {
3560         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
3561         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3562                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3563         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
3564     }
3565 
3566     /* supported_signature_algorithms */
3567 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3568     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
3569     {
3570         size_t sig_alg_len =
3571             ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
3572               | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]   ) );
3573 #if defined(MBEDTLS_DEBUG_C)
3574         unsigned char* sig_alg;
3575         size_t i;
3576 #endif
3577 
3578         /*
3579          * The furthest access in buf is in the loop few lines below:
3580          *     sig_alg[i + 1],
3581          * where:
3582          *     sig_alg = buf + ...hdr_len + 3 + n,
3583          *     max(i) = sig_alg_len - 1.
3584          * Therefore the furthest access is:
3585          *     buf[...hdr_len + 3 + n + sig_alg_len - 1 + 1],
3586          * which reduces to:
3587          *     buf[...hdr_len + 3 + n + sig_alg_len],
3588          * which is one less than we need the buf to be.
3589          */
3590         if( ssl->in_hslen <= mbedtls_ssl_hs_hdr_len( ssl )
3591                                 + 3 + n + sig_alg_len )
3592         {
3593             MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
3594             mbedtls_ssl_send_alert_message(
3595                 ssl,
3596                 MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3597                 MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3598             return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
3599         }
3600 
3601 #if defined(MBEDTLS_DEBUG_C)
3602         sig_alg = buf + mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n;
3603         for( i = 0; i < sig_alg_len; i += 2 )
3604         {
3605             MBEDTLS_SSL_DEBUG_MSG( 3,
3606                 ( "Supported Signature Algorithm found: %d,%d",
3607                   sig_alg[i], sig_alg[i + 1]  ) );
3608         }
3609 #endif
3610 
3611         n += 2 + sig_alg_len;
3612     }
3613 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3614 
3615     /* certificate_authorities */
3616     dn_len = ( ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 1 + n] <<  8 )
3617              | ( buf[mbedtls_ssl_hs_hdr_len( ssl ) + 2 + n]       ) );
3618 
3619     n += dn_len;
3620     if( ssl->in_hslen != mbedtls_ssl_hs_hdr_len( ssl ) + 3 + n )
3621     {
3622         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate request message" ) );
3623         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3624                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3625         return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_REQUEST );
3626     }
3627 
3628 exit:
3629     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate request" ) );
3630 
3631     return( 0 );
3632 }
3633 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
3634 
ssl_parse_server_hello_done(mbedtls_ssl_context * ssl)3635 static int ssl_parse_server_hello_done( mbedtls_ssl_context *ssl )
3636 {
3637     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3638 
3639     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse server hello done" ) );
3640 
3641     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
3642     {
3643         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
3644         return( ret );
3645     }
3646 
3647     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
3648     {
3649         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
3650         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
3651     }
3652 
3653     if( ssl->in_hslen  != mbedtls_ssl_hs_hdr_len( ssl ) ||
3654         ssl->in_msg[0] != MBEDTLS_SSL_HS_SERVER_HELLO_DONE )
3655     {
3656         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad server hello done message" ) );
3657         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3658                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
3659         return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_HELLO_DONE );
3660     }
3661 
3662     ssl->state++;
3663 
3664 #if defined(MBEDTLS_SSL_PROTO_DTLS)
3665     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM )
3666         mbedtls_ssl_recv_flight_completed( ssl );
3667 #endif
3668 
3669     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse server hello done" ) );
3670 
3671     return( 0 );
3672 }
3673 
ssl_write_client_key_exchange(mbedtls_ssl_context * ssl)3674 static int ssl_write_client_key_exchange( mbedtls_ssl_context *ssl )
3675 {
3676     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3677 
3678     size_t header_len;
3679     size_t content_len;
3680     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3681         ssl->handshake->ciphersuite_info;
3682 
3683     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write client key exchange" ) );
3684 
3685 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
3686     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA )
3687     {
3688         /*
3689          * DHM key exchange -- send G^X mod P
3690          */
3691         content_len = ssl->handshake->dhm_ctx.len;
3692 
3693         ssl->out_msg[4] = (unsigned char)( content_len >> 8 );
3694         ssl->out_msg[5] = (unsigned char)( content_len      );
3695         header_len = 6;
3696 
3697         ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
3698                           (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
3699                           &ssl->out_msg[header_len], content_len,
3700                           ssl->conf->f_rng, ssl->conf->p_rng );
3701         if( ret != 0 )
3702         {
3703             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
3704             return( ret );
3705         }
3706 
3707         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X  );
3708         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX );
3709 
3710         if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx,
3711                                   ssl->handshake->premaster,
3712                                   MBEDTLS_PREMASTER_SIZE,
3713                                   &ssl->handshake->pmslen,
3714                                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3715         {
3716             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret );
3717             return( ret );
3718         }
3719 
3720         MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K  );
3721     }
3722     else
3723 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
3724 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&                           \
3725         ( defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||     \
3726           defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) )
3727     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3728         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA )
3729     {
3730         psa_status_t status;
3731         psa_key_attributes_t key_attributes;
3732 
3733         mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3734 
3735         unsigned char own_pubkey[MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH];
3736         size_t own_pubkey_len;
3737         unsigned char *own_pubkey_ecpoint;
3738         size_t own_pubkey_ecpoint_len;
3739 
3740         header_len = 4;
3741 
3742         MBEDTLS_SSL_DEBUG_MSG( 1, ( "Perform PSA-based ECDH computation." ) );
3743 
3744         /*
3745          * Generate EC private key for ECDHE exchange.
3746          */
3747 
3748         /* The master secret is obtained from the shared ECDH secret by
3749          * applying the TLS 1.2 PRF with a specific salt and label. While
3750          * the PSA Crypto API encourages combining key agreement schemes
3751          * such as ECDH with fixed KDFs such as TLS 1.2 PRF, it does not
3752          * yet support the provisioning of salt + label to the KDF.
3753          * For the time being, we therefore need to split the computation
3754          * of the ECDH secret and the application of the TLS 1.2 PRF. */
3755         key_attributes = psa_key_attributes_init();
3756         psa_set_key_usage_flags( &key_attributes, PSA_KEY_USAGE_DERIVE );
3757         psa_set_key_algorithm( &key_attributes, PSA_ALG_ECDH );
3758         psa_set_key_type( &key_attributes, handshake->ecdh_psa_type );
3759         psa_set_key_bits( &key_attributes, handshake->ecdh_bits );
3760 
3761         /* Generate ECDH private key. */
3762         status = psa_generate_key( &key_attributes,
3763                                    &handshake->ecdh_psa_privkey );
3764         if( status != PSA_SUCCESS )
3765             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3766 
3767         /* Export the public part of the ECDH private key from PSA
3768          * and convert it to ECPoint format used in ClientKeyExchange. */
3769         status = psa_export_public_key( handshake->ecdh_psa_privkey,
3770                                         own_pubkey, sizeof( own_pubkey ),
3771                                         &own_pubkey_len );
3772         if( status != PSA_SUCCESS )
3773             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3774 
3775         if( mbedtls_psa_tls_psa_ec_to_ecpoint( own_pubkey,
3776                                                own_pubkey_len,
3777                                                &own_pubkey_ecpoint,
3778                                                &own_pubkey_ecpoint_len ) != 0 )
3779         {
3780             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3781         }
3782 
3783         /* Copy ECPoint structure to outgoing message buffer. */
3784         ssl->out_msg[header_len] = (unsigned char) own_pubkey_ecpoint_len;
3785         memcpy( ssl->out_msg + header_len + 1,
3786                 own_pubkey_ecpoint, own_pubkey_ecpoint_len );
3787         content_len = own_pubkey_ecpoint_len + 1;
3788 
3789         /* The ECDH secret is the premaster secret used for key derivation. */
3790 
3791         /* Compute ECDH shared secret. */
3792         status = psa_raw_key_agreement( PSA_ALG_ECDH,
3793                                         handshake->ecdh_psa_privkey,
3794                                         handshake->ecdh_psa_peerkey,
3795                                         handshake->ecdh_psa_peerkey_len,
3796                                         ssl->handshake->premaster,
3797                                         sizeof( ssl->handshake->premaster ),
3798                                         &ssl->handshake->pmslen );
3799         if( status != PSA_SUCCESS )
3800             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3801 
3802         status = psa_destroy_key( handshake->ecdh_psa_privkey );
3803         if( status != PSA_SUCCESS )
3804             return( MBEDTLS_ERR_SSL_HW_ACCEL_FAILED );
3805         handshake->ecdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3806     }
3807     else
3808 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
3809             ( MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3810               MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ) */
3811 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
3812     defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
3813     defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
3814     defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
3815     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3816         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
3817         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
3818         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA )
3819     {
3820         /*
3821          * ECDH key exchange -- send client public value
3822          */
3823         header_len = 4;
3824 
3825 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3826         if( ssl->handshake->ecrs_enabled )
3827         {
3828             if( ssl->handshake->ecrs_state == ssl_ecrs_cke_ecdh_calc_secret )
3829                 goto ecdh_calc_secret;
3830 
3831             mbedtls_ecdh_enable_restart( &ssl->handshake->ecdh_ctx );
3832         }
3833 #endif
3834 
3835         ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
3836                                 &content_len,
3837                                 &ssl->out_msg[header_len], 1000,
3838                                 ssl->conf->f_rng, ssl->conf->p_rng );
3839         if( ret != 0 )
3840         {
3841             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
3842 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3843             if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
3844                 ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
3845 #endif
3846             return( ret );
3847         }
3848 
3849         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
3850                                 MBEDTLS_DEBUG_ECDH_Q );
3851 
3852 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3853         if( ssl->handshake->ecrs_enabled )
3854         {
3855             ssl->handshake->ecrs_n = content_len;
3856             ssl->handshake->ecrs_state = ssl_ecrs_cke_ecdh_calc_secret;
3857         }
3858 
3859 ecdh_calc_secret:
3860         if( ssl->handshake->ecrs_enabled )
3861             content_len = ssl->handshake->ecrs_n;
3862 #endif
3863         if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx,
3864                                   &ssl->handshake->pmslen,
3865                                   ssl->handshake->premaster,
3866                                   MBEDTLS_MPI_MAX_SIZE,
3867                                   ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 )
3868         {
3869             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret );
3870 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3871             if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
3872                 ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
3873 #endif
3874             return( ret );
3875         }
3876 
3877         MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
3878                                 MBEDTLS_DEBUG_ECDH_Z );
3879     }
3880     else
3881 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3882           MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
3883           MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
3884           MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3885 #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
3886     if( mbedtls_ssl_ciphersuite_uses_psk( ciphersuite_info ) )
3887     {
3888         /*
3889          * opaque psk_identity<0..2^16-1>;
3890          */
3891         if( ssl_conf_has_static_psk( ssl->conf ) == 0 )
3892         {
3893             /* We don't offer PSK suites if we don't have a PSK,
3894              * and we check that the server's choice is among the
3895              * ciphersuites we offered, so this should never happen. */
3896             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
3897         }
3898 
3899         header_len = 4;
3900         content_len = ssl->conf->psk_identity_len;
3901 
3902         if( header_len + 2 + content_len > MBEDTLS_SSL_OUT_CONTENT_LEN )
3903         {
3904             MBEDTLS_SSL_DEBUG_MSG( 1,
3905                 ( "psk identity too long or SSL buffer too short" ) );
3906             return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3907         }
3908 
3909         ssl->out_msg[header_len++] = (unsigned char)( content_len >> 8 );
3910         ssl->out_msg[header_len++] = (unsigned char)( content_len      );
3911 
3912         memcpy( ssl->out_msg + header_len,
3913                 ssl->conf->psk_identity,
3914                 ssl->conf->psk_identity_len );
3915         header_len += ssl->conf->psk_identity_len;
3916 
3917 #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
3918         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK )
3919         {
3920             content_len = 0;
3921         }
3922         else
3923 #endif
3924 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3925         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK )
3926         {
3927 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3928             /* Opaque PSKs are currently only supported for PSK-only suites. */
3929             if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 )
3930                 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3931 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3932 
3933             if( ( ret = ssl_write_encrypted_pms( ssl, header_len,
3934                                                  &content_len, 2 ) ) != 0 )
3935                 return( ret );
3936         }
3937         else
3938 #endif
3939 #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3940         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK )
3941         {
3942 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3943             /* Opaque PSKs are currently only supported for PSK-only suites. */
3944             if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 )
3945                 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3946 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3947 
3948             /*
3949              * ClientDiffieHellmanPublic public (DHM send G^X mod P)
3950              */
3951             content_len = ssl->handshake->dhm_ctx.len;
3952 
3953             if( header_len + 2 + content_len >
3954                 MBEDTLS_SSL_OUT_CONTENT_LEN )
3955             {
3956                 MBEDTLS_SSL_DEBUG_MSG( 1,
3957                     ( "psk identity or DHM size too long or SSL buffer too short" ) );
3958                 return( MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL );
3959             }
3960 
3961             ssl->out_msg[header_len++] = (unsigned char)( content_len >> 8 );
3962             ssl->out_msg[header_len++] = (unsigned char)( content_len      );
3963 
3964             ret = mbedtls_dhm_make_public( &ssl->handshake->dhm_ctx,
3965                     (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ),
3966                     &ssl->out_msg[header_len], content_len,
3967                     ssl->conf->f_rng, ssl->conf->p_rng );
3968             if( ret != 0 )
3969             {
3970                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_public", ret );
3971                 return( ret );
3972             }
3973         }
3974         else
3975 #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3976 #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3977         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK )
3978         {
3979 #if defined(MBEDTLS_USE_PSA_CRYPTO)
3980             /* Opaque PSKs are currently only supported for PSK-only suites. */
3981             if( ssl_conf_has_static_raw_psk( ssl->conf ) == 0 )
3982                 return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE );
3983 #endif /* MBEDTLS_USE_PSA_CRYPTO */
3984 
3985             /*
3986              * ClientECDiffieHellmanPublic public;
3987              */
3988             ret = mbedtls_ecdh_make_public( &ssl->handshake->ecdh_ctx,
3989                     &content_len,
3990                     &ssl->out_msg[header_len],
3991                     MBEDTLS_SSL_OUT_CONTENT_LEN - header_len,
3992                     ssl->conf->f_rng, ssl->conf->p_rng );
3993             if( ret != 0 )
3994             {
3995                 MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_public", ret );
3996                 return( ret );
3997             }
3998 
3999             MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx,
4000                                     MBEDTLS_DEBUG_ECDH_Q );
4001         }
4002         else
4003 #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
4004         {
4005             MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4006             return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4007         }
4008 
4009 #if defined(MBEDTLS_USE_PSA_CRYPTO) &&          \
4010     defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
4011         if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK &&
4012             ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
4013             ssl_conf_has_static_raw_psk( ssl->conf ) == 0 )
4014         {
4015             MBEDTLS_SSL_DEBUG_MSG( 1,
4016                 ( "skip PMS generation for opaque PSK" ) );
4017         }
4018         else
4019 #endif /* MBEDTLS_USE_PSA_CRYPTO &&
4020           MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
4021         if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl,
4022                         ciphersuite_info->key_exchange ) ) != 0 )
4023         {
4024             MBEDTLS_SSL_DEBUG_RET( 1,
4025                 "mbedtls_ssl_psk_derive_premaster", ret );
4026             return( ret );
4027         }
4028     }
4029     else
4030 #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
4031 #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
4032     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA )
4033     {
4034         header_len = 4;
4035         if( ( ret = ssl_write_encrypted_pms( ssl, header_len,
4036                                              &content_len, 0 ) ) != 0 )
4037             return( ret );
4038     }
4039     else
4040 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
4041 #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4042     if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE )
4043     {
4044         header_len = 4;
4045 
4046         ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx,
4047                 ssl->out_msg + header_len,
4048                 MBEDTLS_SSL_OUT_CONTENT_LEN - header_len,
4049                 &content_len,
4050                 ssl->conf->f_rng, ssl->conf->p_rng );
4051         if( ret != 0 )
4052         {
4053             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret );
4054             return( ret );
4055         }
4056 
4057         ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx,
4058                 ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
4059                 ssl->conf->f_rng, ssl->conf->p_rng );
4060         if( ret != 0 )
4061         {
4062             MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret );
4063             return( ret );
4064         }
4065     }
4066     else
4067 #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
4068     {
4069         ((void) ciphersuite_info);
4070         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4071         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4072     }
4073 
4074     ssl->out_msglen  = header_len + content_len;
4075     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4076     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE;
4077 
4078     ssl->state++;
4079 
4080     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
4081     {
4082         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
4083         return( ret );
4084     }
4085 
4086     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write client key exchange" ) );
4087 
4088     return( 0 );
4089 }
4090 
4091 #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
ssl_write_certificate_verify(mbedtls_ssl_context * ssl)4092 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
4093 {
4094     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4095         ssl->handshake->ciphersuite_info;
4096     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4097 
4098     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
4099 
4100     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
4101     {
4102         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
4103         return( ret );
4104     }
4105 
4106     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
4107     {
4108         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
4109         ssl->state++;
4110         return( 0 );
4111     }
4112 
4113     MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4114     return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4115 }
4116 #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
ssl_write_certificate_verify(mbedtls_ssl_context * ssl)4117 static int ssl_write_certificate_verify( mbedtls_ssl_context *ssl )
4118 {
4119     int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4120     const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4121         ssl->handshake->ciphersuite_info;
4122     size_t n = 0, offset = 0;
4123     unsigned char hash[48];
4124     unsigned char *hash_start = hash;
4125     mbedtls_md_type_t md_alg = MBEDTLS_MD_NONE;
4126     size_t hashlen;
4127     void *rs_ctx = NULL;
4128 
4129     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate verify" ) );
4130 
4131 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
4132     if( ssl->handshake->ecrs_enabled &&
4133         ssl->handshake->ecrs_state == ssl_ecrs_crt_vrfy_sign )
4134     {
4135         goto sign;
4136     }
4137 #endif
4138 
4139     if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 )
4140     {
4141         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret );
4142         return( ret );
4143     }
4144 
4145     if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) )
4146     {
4147         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
4148         ssl->state++;
4149         return( 0 );
4150     }
4151 
4152     if( ssl->client_auth == 0 || mbedtls_ssl_own_cert( ssl ) == NULL )
4153     {
4154         MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate verify" ) );
4155         ssl->state++;
4156         return( 0 );
4157     }
4158 
4159     if( mbedtls_ssl_own_key( ssl ) == NULL )
4160     {
4161         MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key for certificate" ) );
4162         return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED );
4163     }
4164 
4165     /*
4166      * Make a signature of the handshake digests
4167      */
4168 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
4169     if( ssl->handshake->ecrs_enabled )
4170         ssl->handshake->ecrs_state = ssl_ecrs_crt_vrfy_sign;
4171 
4172 sign:
4173 #endif
4174 
4175     ssl->handshake->calc_verify( ssl, hash, &hashlen );
4176 
4177 #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
4178     defined(MBEDTLS_SSL_PROTO_TLS1_1)
4179     if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 )
4180     {
4181         /*
4182          * digitally-signed struct {
4183          *     opaque md5_hash[16];
4184          *     opaque sha_hash[20];
4185          * };
4186          *
4187          * md5_hash
4188          *     MD5(handshake_messages);
4189          *
4190          * sha_hash
4191          *     SHA(handshake_messages);
4192          */
4193         md_alg = MBEDTLS_MD_NONE;
4194 
4195         /*
4196          * For ECDSA, default hash is SHA-1 only
4197          */
4198         if( mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECDSA ) )
4199         {
4200             hash_start += 16;
4201             hashlen -= 16;
4202             md_alg = MBEDTLS_MD_SHA1;
4203         }
4204     }
4205     else
4206 #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
4207           MBEDTLS_SSL_PROTO_TLS1_1 */
4208 #if defined(MBEDTLS_SSL_PROTO_TLS1_2)
4209     if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 )
4210     {
4211         /*
4212          * digitally-signed struct {
4213          *     opaque handshake_messages[handshake_messages_length];
4214          * };
4215          *
4216          * Taking shortcut here. We assume that the server always allows the
4217          * PRF Hash function and has sent it in the allowed signature
4218          * algorithms list received in the Certificate Request message.
4219          *
4220          * Until we encounter a server that does not, we will take this
4221          * shortcut.
4222          *
4223          * Reason: Otherwise we should have running hashes for SHA512 and
4224          *         SHA224 in order to satisfy 'weird' needs from the server
4225          *         side.
4226          */
4227         if( ssl->handshake->ciphersuite_info->mac == MBEDTLS_MD_SHA384 )
4228         {
4229             md_alg = MBEDTLS_MD_SHA384;
4230             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA384;
4231         }
4232         else
4233         {
4234             md_alg = MBEDTLS_MD_SHA256;
4235             ssl->out_msg[4] = MBEDTLS_SSL_HASH_SHA256;
4236         }
4237         ssl->out_msg[5] = mbedtls_ssl_sig_from_pk( mbedtls_ssl_own_key( ssl ) );
4238 
4239         /* Info from md_alg will be used instead */
4240         hashlen = 0;
4241         offset = 2;
4242     }
4243     else
4244 #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
4245     {
4246         MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) );
4247         return( MBEDTLS_ERR_SSL_INTERNAL_ERROR );
4248     }
4249 
4250 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
4251     if( ssl->handshake->ecrs_enabled )
4252         rs_ctx = &ssl->handshake->ecrs_ctx.pk;
4253 #endif
4254 
4255     if( ( ret = mbedtls_pk_sign_restartable( mbedtls_ssl_own_key( ssl ),
4256                          md_alg, hash_start, hashlen,
4257                          ssl->out_msg + 6 + offset, &n,
4258                          ssl->conf->f_rng, ssl->conf->p_rng, rs_ctx ) ) != 0 )
4259     {
4260         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret );
4261 #if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
4262         if( ret == MBEDTLS_ERR_ECP_IN_PROGRESS )
4263             ret = MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
4264 #endif
4265         return( ret );
4266     }
4267 
4268     ssl->out_msg[4 + offset] = (unsigned char)( n >> 8 );
4269     ssl->out_msg[5 + offset] = (unsigned char)( n      );
4270 
4271     ssl->out_msglen  = 6 + n + offset;
4272     ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4273     ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_VERIFY;
4274 
4275     ssl->state++;
4276 
4277     if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 )
4278     {
4279         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret );
4280         return( ret );
4281     }
4282 
4283     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate verify" ) );
4284 
4285     return( ret );
4286 }
4287 #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4288 
4289 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
ssl_parse_new_session_ticket(mbedtls_ssl_context * ssl)4290 static int ssl_parse_new_session_ticket( mbedtls_ssl_context *ssl )
4291 {
4292     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4293     uint32_t lifetime;
4294     size_t ticket_len;
4295     unsigned char *ticket;
4296     const unsigned char *msg;
4297 
4298     MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse new session ticket" ) );
4299 
4300     if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 )
4301     {
4302         MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret );
4303         return( ret );
4304     }
4305 
4306     if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE )
4307     {
4308         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
4309         mbedtls_ssl_send_alert_message(
4310             ssl,
4311             MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4312             MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE );
4313         return( MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE );
4314     }
4315 
4316     /*
4317      * struct {
4318      *     uint32 ticket_lifetime_hint;
4319      *     opaque ticket<0..2^16-1>;
4320      * } NewSessionTicket;
4321      *
4322      * 0  .  3   ticket_lifetime_hint
4323      * 4  .  5   ticket_len (n)
4324      * 6  .  5+n ticket content
4325      */
4326     if( ssl->in_msg[0] != MBEDTLS_SSL_HS_NEW_SESSION_TICKET ||
4327         ssl->in_hslen < 6 + mbedtls_ssl_hs_hdr_len( ssl ) )
4328     {
4329         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
4330         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4331                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4332         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
4333     }
4334 
4335     msg = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl );
4336 
4337     lifetime = ( ((uint32_t) msg[0]) << 24 ) | ( msg[1] << 16 ) |
4338                ( msg[2] << 8 ) | ( msg[3] );
4339 
4340     ticket_len = ( msg[4] << 8 ) | ( msg[5] );
4341 
4342     if( ticket_len + 6 + mbedtls_ssl_hs_hdr_len( ssl ) != ssl->in_hslen )
4343     {
4344         MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad new session ticket message" ) );
4345         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4346                                         MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR );
4347         return( MBEDTLS_ERR_SSL_BAD_HS_NEW_SESSION_TICKET );
4348     }
4349 
4350     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", ticket_len ) );
4351 
4352     /* We're not waiting for a NewSessionTicket message any more */
4353     ssl->handshake->new_session_ticket = 0;
4354     ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
4355 
4356     /*
4357      * Zero-length ticket means the server changed his mind and doesn't want
4358      * to send a ticket after all, so just forget it
4359      */
4360     if( ticket_len == 0 )
4361         return( 0 );
4362 
4363     if( ssl->session != NULL && ssl->session->ticket != NULL )
4364     {
4365         mbedtls_platform_zeroize( ssl->session->ticket,
4366                                   ssl->session->ticket_len );
4367         mbedtls_free( ssl->session->ticket );
4368         ssl->session->ticket = NULL;
4369         ssl->session->ticket_len = 0;
4370     }
4371 
4372     mbedtls_platform_zeroize( ssl->session_negotiate->ticket,
4373                               ssl->session_negotiate->ticket_len );
4374     mbedtls_free( ssl->session_negotiate->ticket );
4375     ssl->session_negotiate->ticket = NULL;
4376     ssl->session_negotiate->ticket_len = 0;
4377 
4378     if( ( ticket = mbedtls_calloc( 1, ticket_len ) ) == NULL )
4379     {
4380         MBEDTLS_SSL_DEBUG_MSG( 1, ( "ticket alloc failed" ) );
4381         mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
4382                                         MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR );
4383         return( MBEDTLS_ERR_SSL_ALLOC_FAILED );
4384     }
4385 
4386     memcpy( ticket, msg + 6, ticket_len );
4387 
4388     ssl->session_negotiate->ticket = ticket;
4389     ssl->session_negotiate->ticket_len = ticket_len;
4390     ssl->session_negotiate->ticket_lifetime = lifetime;
4391 
4392     /*
4393      * RFC 5077 section 3.4:
4394      * "If the client receives a session ticket from the server, then it
4395      * discards any Session ID that was sent in the ServerHello."
4396      */
4397     MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket in use, discarding session id" ) );
4398     ssl->session_negotiate->id_len = 0;
4399 
4400     MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse new session ticket" ) );
4401 
4402     return( 0 );
4403 }
4404 #endif /* MBEDTLS_SSL_SESSION_TICKETS */
4405 
4406 /*
4407  * SSL handshake -- client side -- single step
4408  */
mbedtls_ssl_handshake_client_step(mbedtls_ssl_context * ssl)4409 int mbedtls_ssl_handshake_client_step( mbedtls_ssl_context *ssl )
4410 {
4411     int ret = 0;
4412 
4413     if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL )
4414         return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4415 
4416     MBEDTLS_SSL_DEBUG_MSG( 2, ( "client state: %d", ssl->state ) );
4417 
4418     if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 )
4419         return( ret );
4420 
4421 #if defined(MBEDTLS_SSL_PROTO_DTLS)
4422     if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
4423         ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING )
4424     {
4425         if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 )
4426             return( ret );
4427     }
4428 #endif /* MBEDTLS_SSL_PROTO_DTLS */
4429 
4430     /* Change state now, so that it is right in mbedtls_ssl_read_record(), used
4431      * by DTLS for dropping out-of-sequence ChangeCipherSpec records */
4432 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
4433     if( ssl->state == MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC &&
4434         ssl->handshake->new_session_ticket != 0 )
4435     {
4436         ssl->state = MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET;
4437     }
4438 #endif
4439 
4440     switch( ssl->state )
4441     {
4442         case MBEDTLS_SSL_HELLO_REQUEST:
4443             ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
4444             break;
4445 
4446        /*
4447         *  ==>   ClientHello
4448         */
4449        case MBEDTLS_SSL_CLIENT_HELLO:
4450            ret = ssl_write_client_hello( ssl );
4451            break;
4452 
4453        /*
4454         *  <==   ServerHello
4455         *        Certificate
4456         *      ( ServerKeyExchange  )
4457         *      ( CertificateRequest )
4458         *        ServerHelloDone
4459         */
4460        case MBEDTLS_SSL_SERVER_HELLO:
4461            ret = ssl_parse_server_hello( ssl );
4462            break;
4463 
4464        case MBEDTLS_SSL_SERVER_CERTIFICATE:
4465            ret = mbedtls_ssl_parse_certificate( ssl );
4466            break;
4467 
4468        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
4469            ret = ssl_parse_server_key_exchange( ssl );
4470            break;
4471 
4472        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
4473            ret = ssl_parse_certificate_request( ssl );
4474            break;
4475 
4476        case MBEDTLS_SSL_SERVER_HELLO_DONE:
4477            ret = ssl_parse_server_hello_done( ssl );
4478            break;
4479 
4480        /*
4481         *  ==> ( Certificate/Alert  )
4482         *        ClientKeyExchange
4483         *      ( CertificateVerify  )
4484         *        ChangeCipherSpec
4485         *        Finished
4486         */
4487        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
4488            ret = mbedtls_ssl_write_certificate( ssl );
4489            break;
4490 
4491        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
4492            ret = ssl_write_client_key_exchange( ssl );
4493            break;
4494 
4495        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
4496            ret = ssl_write_certificate_verify( ssl );
4497            break;
4498 
4499        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
4500            ret = mbedtls_ssl_write_change_cipher_spec( ssl );
4501            break;
4502 
4503        case MBEDTLS_SSL_CLIENT_FINISHED:
4504            ret = mbedtls_ssl_write_finished( ssl );
4505            break;
4506 
4507        /*
4508         *  <==   ( NewSessionTicket )
4509         *        ChangeCipherSpec
4510         *        Finished
4511         */
4512 #if defined(MBEDTLS_SSL_SESSION_TICKETS)
4513        case MBEDTLS_SSL_SERVER_NEW_SESSION_TICKET:
4514            ret = ssl_parse_new_session_ticket( ssl );
4515            break;
4516 #endif
4517 
4518        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
4519            ret = mbedtls_ssl_parse_change_cipher_spec( ssl );
4520            break;
4521 
4522        case MBEDTLS_SSL_SERVER_FINISHED:
4523            ret = mbedtls_ssl_parse_finished( ssl );
4524            break;
4525 
4526        case MBEDTLS_SSL_FLUSH_BUFFERS:
4527            MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) );
4528            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
4529            break;
4530 
4531        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
4532            mbedtls_ssl_handshake_wrapup( ssl );
4533            break;
4534 
4535        default:
4536            MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) );
4537            return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA );
4538    }
4539 
4540     return( ret );
4541 }
4542 #endif /* MBEDTLS_SSL_CLI_C */
4543