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