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