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