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