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