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 "debug_internal.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)
29static 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)
48int 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
68void 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)
80MBEDTLS_CHECK_RETURN_CRITICAL
81static 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
106MBEDTLS_CHECK_RETURN_CRITICAL
107static 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 */
180MBEDTLS_CHECK_RETURN_CRITICAL
181static 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 = MBEDTLS_GET_UINT16_BE(buf, 0);
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
245MBEDTLS_CHECK_RETURN_CRITICAL
246static 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)
289MBEDTLS_CHECK_RETURN_CRITICAL
290static 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)
339MBEDTLS_CHECK_RETURN_CRITICAL
340static 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)
358MBEDTLS_CHECK_RETURN_CRITICAL
359static 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)
423MBEDTLS_CHECK_RETURN_CRITICAL
424static 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)
446MBEDTLS_CHECK_RETURN_CRITICAL
447static 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)
469MBEDTLS_CHECK_RETURN_CRITICAL
470static 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)
543MBEDTLS_CHECK_RETURN_CRITICAL
544static 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)
662MBEDTLS_CHECK_RETURN_CRITICAL
663static 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_get_ec_group_id(pk);
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 */
686MBEDTLS_CHECK_RETURN_CRITICAL
687static 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 */
794MBEDTLS_CHECK_RETURN_CRITICAL
795static 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. */
886MBEDTLS_CHECK_RETURN_CRITICAL
887static 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)
916read_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                              MBEDTLS_GET_UINT16_BE(ssl->in_len, 0)));
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 = MBEDTLS_GET_UINT16_BE(ssl->in_len, 0);
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 layout:
1132     *     0  .   1   protocol version
1133     *     2  .  33   random bytes (starting with 4 bytes of Unix time)
1134     *    34  .  34   session id length (1 byte)
1135     *    35  . 34+x  session id, where x = session id length from byte 34
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    ssl->session_negotiate->endpoint = ssl->conf->endpoint;
1165
1166    if (ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_2) {
1167        MBEDTLS_SSL_DEBUG_MSG(1, ("server only supports TLS 1.2"));
1168        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1169                                       MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1170        return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1171    }
1172
1173    /*
1174     * Save client random (inc. Unix time)
1175     */
1176    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, random bytes", buf + 2, 32);
1177
1178    memcpy(ssl->handshake->randbytes, buf + 2, 32);
1179
1180    /*
1181     * Check the session ID length and save session ID
1182     */
1183    sess_len = buf[34];
1184
1185    if (sess_len > sizeof(ssl->session_negotiate->id) ||
1186        sess_len + 34 + 2 > msg_len) { /* 2 for cipherlist length field */
1187        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1188        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1189                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1190        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1191    }
1192
1193    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, session id", buf + 35, sess_len);
1194
1195    ssl->session_negotiate->id_len = sess_len;
1196    memset(ssl->session_negotiate->id, 0,
1197           sizeof(ssl->session_negotiate->id));
1198    memcpy(ssl->session_negotiate->id, buf + 35,
1199           ssl->session_negotiate->id_len);
1200
1201    /*
1202     * Check the cookie length and content
1203     */
1204#if defined(MBEDTLS_SSL_PROTO_DTLS)
1205    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1206        cookie_offset = 35 + sess_len;
1207        cookie_len = buf[cookie_offset];
1208
1209        if (cookie_offset + 1 + cookie_len + 2 > msg_len) {
1210            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1211            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1212                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1213            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1214        }
1215
1216        MBEDTLS_SSL_DEBUG_BUF(3, "client hello, cookie",
1217                              buf + cookie_offset + 1, cookie_len);
1218
1219#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
1220        if (ssl->conf->f_cookie_check != NULL
1221#if defined(MBEDTLS_SSL_RENEGOTIATION)
1222            && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
1223#endif
1224            ) {
1225            if (ssl->conf->f_cookie_check(ssl->conf->p_cookie,
1226                                          buf + cookie_offset + 1, cookie_len,
1227                                          ssl->cli_id, ssl->cli_id_len) != 0) {
1228                MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification failed"));
1229                ssl->handshake->cookie_verify_result = 1;
1230            } else {
1231                MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification passed"));
1232                ssl->handshake->cookie_verify_result = 0;
1233            }
1234        } else
1235#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
1236        {
1237            /* We know we didn't send a cookie, so it should be empty */
1238            if (cookie_len != 0) {
1239                /* This may be an attacker's probe, so don't send an alert */
1240                MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1241                return MBEDTLS_ERR_SSL_DECODE_ERROR;
1242            }
1243
1244            MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification skipped"));
1245        }
1246
1247        /*
1248         * Check the ciphersuitelist length (will be parsed later)
1249         */
1250        ciph_offset = cookie_offset + 1 + cookie_len;
1251    } else
1252#endif /* MBEDTLS_SSL_PROTO_DTLS */
1253    ciph_offset = 35 + sess_len;
1254
1255    ciph_len = MBEDTLS_GET_UINT16_BE(buf, ciph_offset);
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 = MBEDTLS_GET_UINT16_BE(buf, ext_offset);
1304
1305        if (msg_len != ext_offset + 2 + ext_len) {
1306            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1307            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1308                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1309            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1310        }
1311    } else {
1312        ext_len = 0;
1313    }
1314
1315    ext = buf + ext_offset + 2;
1316    MBEDTLS_SSL_DEBUG_BUF(3, "client hello extensions", ext, ext_len);
1317
1318    while (ext_len != 0) {
1319        unsigned int ext_id;
1320        unsigned int ext_size;
1321        if (ext_len < 4) {
1322            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1323            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1324                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1325            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1326        }
1327        ext_id   = MBEDTLS_GET_UINT16_BE(ext, 0);
1328        ext_size = MBEDTLS_GET_UINT16_BE(ext, 2);
1329
1330        if (ext_size + 4 > ext_len) {
1331            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1332            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1333                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1334            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1335        }
1336        switch (ext_id) {
1337#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1338            case MBEDTLS_TLS_EXT_SERVERNAME:
1339                MBEDTLS_SSL_DEBUG_MSG(3, ("found ServerName extension"));
1340                ret = mbedtls_ssl_parse_server_name_ext(ssl, ext + 4,
1341                                                        ext + 4 + ext_size);
1342                if (ret != 0) {
1343                    return ret;
1344                }
1345                break;
1346#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1347
1348            case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1349                MBEDTLS_SSL_DEBUG_MSG(3, ("found renegotiation extension"));
1350#if defined(MBEDTLS_SSL_RENEGOTIATION)
1351                renegotiation_info_seen = 1;
1352#endif
1353
1354                ret = ssl_parse_renegotiation_info(ssl, ext + 4, ext_size);
1355                if (ret != 0) {
1356                    return ret;
1357                }
1358                break;
1359
1360#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1361            case MBEDTLS_TLS_EXT_SIG_ALG:
1362                MBEDTLS_SSL_DEBUG_MSG(3, ("found signature_algorithms extension"));
1363
1364                ret = mbedtls_ssl_parse_sig_alg_ext(ssl, ext + 4, ext + 4 + ext_size);
1365                if (ret != 0) {
1366                    return ret;
1367                }
1368
1369                sig_hash_alg_ext_present = 1;
1370                break;
1371#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1372
1373#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
1374                defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
1375                defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1376            case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
1377                MBEDTLS_SSL_DEBUG_MSG(3, ("found supported elliptic curves extension"));
1378
1379                ret = ssl_parse_supported_groups_ext(ssl, ext + 4, ext_size);
1380                if (ret != 0) {
1381                    return ret;
1382                }
1383                break;
1384
1385            case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1386                MBEDTLS_SSL_DEBUG_MSG(3, ("found supported point formats extension"));
1387                ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
1388
1389                ret = ssl_parse_supported_point_formats(ssl, ext + 4, ext_size);
1390                if (ret != 0) {
1391                    return ret;
1392                }
1393                break;
1394#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED || \
1395          MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED ||
1396          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1397
1398#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1399            case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1400                MBEDTLS_SSL_DEBUG_MSG(3, ("found ecjpake kkpp extension"));
1401
1402                ret = ssl_parse_ecjpake_kkpp(ssl, ext + 4, ext_size);
1403                if (ret != 0) {
1404                    return ret;
1405                }
1406                break;
1407#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1408
1409#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1410            case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1411                MBEDTLS_SSL_DEBUG_MSG(3, ("found max fragment length extension"));
1412
1413                ret = ssl_parse_max_fragment_length_ext(ssl, ext + 4, ext_size);
1414                if (ret != 0) {
1415                    return ret;
1416                }
1417                break;
1418#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1419
1420#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1421            case MBEDTLS_TLS_EXT_CID:
1422                MBEDTLS_SSL_DEBUG_MSG(3, ("found CID extension"));
1423
1424                ret = ssl_parse_cid_ext(ssl, ext + 4, ext_size);
1425                if (ret != 0) {
1426                    return ret;
1427                }
1428                break;
1429#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1430
1431#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1432            case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
1433                MBEDTLS_SSL_DEBUG_MSG(3, ("found encrypt then mac extension"));
1434
1435                ret = ssl_parse_encrypt_then_mac_ext(ssl, ext + 4, ext_size);
1436                if (ret != 0) {
1437                    return ret;
1438                }
1439                break;
1440#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1441
1442#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1443            case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
1444                MBEDTLS_SSL_DEBUG_MSG(3, ("found extended master secret extension"));
1445
1446                ret = ssl_parse_extended_ms_ext(ssl, ext + 4, ext_size);
1447                if (ret != 0) {
1448                    return ret;
1449                }
1450                break;
1451#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1452
1453#if defined(MBEDTLS_SSL_SESSION_TICKETS)
1454            case MBEDTLS_TLS_EXT_SESSION_TICKET:
1455                MBEDTLS_SSL_DEBUG_MSG(3, ("found session ticket extension"));
1456
1457                ret = ssl_parse_session_ticket_ext(ssl, ext + 4, ext_size);
1458                if (ret != 0) {
1459                    return ret;
1460                }
1461                break;
1462#endif /* MBEDTLS_SSL_SESSION_TICKETS */
1463
1464#if defined(MBEDTLS_SSL_ALPN)
1465            case MBEDTLS_TLS_EXT_ALPN:
1466                MBEDTLS_SSL_DEBUG_MSG(3, ("found alpn extension"));
1467
1468                ret = mbedtls_ssl_parse_alpn_ext(ssl, ext + 4,
1469                                                 ext + 4 + ext_size);
1470                if (ret != 0) {
1471                    return ret;
1472                }
1473                break;
1474#endif /* MBEDTLS_SSL_SESSION_TICKETS */
1475
1476#if defined(MBEDTLS_SSL_DTLS_SRTP)
1477            case MBEDTLS_TLS_EXT_USE_SRTP:
1478                MBEDTLS_SSL_DEBUG_MSG(3, ("found use_srtp extension"));
1479
1480                ret = ssl_parse_use_srtp_ext(ssl, ext + 4, ext_size);
1481                if (ret != 0) {
1482                    return ret;
1483                }
1484                break;
1485#endif /* MBEDTLS_SSL_DTLS_SRTP */
1486
1487            default:
1488                MBEDTLS_SSL_DEBUG_MSG(3, ("unknown extension found: %u (ignoring)",
1489                                          ext_id));
1490        }
1491
1492        ext_len -= 4 + ext_size;
1493        ext += 4 + ext_size;
1494    }
1495
1496#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1497
1498    /*
1499     * Try to fall back to default hash SHA1 if the client
1500     * hasn't provided any preferred signature-hash combinations.
1501     */
1502    if (!sig_hash_alg_ext_present) {
1503        uint16_t *received_sig_algs = ssl->handshake->received_sig_algs;
1504        const uint16_t default_sig_algs[] = {
1505#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
1506            MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG(MBEDTLS_SSL_SIG_ECDSA,
1507                                               MBEDTLS_SSL_HASH_SHA1),
1508#endif
1509#if defined(MBEDTLS_RSA_C)
1510            MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG(MBEDTLS_SSL_SIG_RSA,
1511                                               MBEDTLS_SSL_HASH_SHA1),
1512#endif
1513            MBEDTLS_TLS_SIG_NONE
1514        };
1515
1516        MBEDTLS_STATIC_ASSERT(sizeof(default_sig_algs) / sizeof(default_sig_algs[0])
1517                              <= MBEDTLS_RECEIVED_SIG_ALGS_SIZE,
1518                              "default_sig_algs is too big");
1519
1520        memcpy(received_sig_algs, default_sig_algs, sizeof(default_sig_algs));
1521    }
1522
1523#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1524
1525    /*
1526     * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1527     */
1528    for (i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2) {
1529        if (p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO) {
1530            MBEDTLS_SSL_DEBUG_MSG(3, ("received TLS_EMPTY_RENEGOTIATION_INFO "));
1531#if defined(MBEDTLS_SSL_RENEGOTIATION)
1532            if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
1533                MBEDTLS_SSL_DEBUG_MSG(1, ("received RENEGOTIATION SCSV "
1534                                          "during renegotiation"));
1535                mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1536                                               MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1537                return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1538            }
1539#endif
1540            ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
1541            break;
1542        }
1543    }
1544
1545    /*
1546     * Renegotiation security checks
1547     */
1548    if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1549        ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE) {
1550        MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation, breaking off handshake"));
1551        handshake_failure = 1;
1552    }
1553#if defined(MBEDTLS_SSL_RENEGOTIATION)
1554    else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1555             ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1556             renegotiation_info_seen == 0) {
1557        MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation_info extension missing (secure)"));
1558        handshake_failure = 1;
1559    } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1560               ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1561               ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION) {
1562        MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation not allowed"));
1563        handshake_failure = 1;
1564    } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1565               ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1566               renegotiation_info_seen == 1) {
1567        MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation_info extension present (legacy)"));
1568        handshake_failure = 1;
1569    }
1570#endif /* MBEDTLS_SSL_RENEGOTIATION */
1571
1572    if (handshake_failure == 1) {
1573        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1574                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1575        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1576    }
1577
1578    /*
1579     * Server certification selection (after processing TLS extensions)
1580     */
1581    if (ssl->conf->f_cert_cb && (ret = ssl->conf->f_cert_cb(ssl)) != 0) {
1582        MBEDTLS_SSL_DEBUG_RET(1, "f_cert_cb", ret);
1583        return ret;
1584    }
1585#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1586    ssl->handshake->sni_name = NULL;
1587    ssl->handshake->sni_name_len = 0;
1588#endif
1589
1590    /*
1591     * Search for a matching ciphersuite
1592     * (At the end because we need information from the EC-based extensions
1593     * and certificate from the SNI callback triggered by the SNI extension
1594     * or certificate from server certificate selection callback.)
1595     */
1596    got_common_suite = 0;
1597    ciphersuites = ssl->conf->ciphersuite_list;
1598    ciphersuite_info = NULL;
1599
1600    if (ssl->conf->respect_cli_pref == MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_CLIENT) {
1601        for (j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2) {
1602            for (i = 0; ciphersuites[i] != 0; i++) {
1603                if (MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i]) {
1604                    continue;
1605                }
1606
1607                got_common_suite = 1;
1608
1609                if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
1610                                                 &ciphersuite_info)) != 0) {
1611                    return ret;
1612                }
1613
1614                if (ciphersuite_info != NULL) {
1615                    goto have_ciphersuite;
1616                }
1617            }
1618        }
1619    } else {
1620        for (i = 0; ciphersuites[i] != 0; i++) {
1621            for (j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2) {
1622                if (MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i]) {
1623                    continue;
1624                }
1625
1626                got_common_suite = 1;
1627
1628                if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
1629                                                 &ciphersuite_info)) != 0) {
1630                    return ret;
1631                }
1632
1633                if (ciphersuite_info != NULL) {
1634                    goto have_ciphersuite;
1635                }
1636            }
1637        }
1638    }
1639
1640    if (got_common_suite) {
1641        MBEDTLS_SSL_DEBUG_MSG(1, ("got ciphersuites in common, "
1642                                  "but none of them usable"));
1643        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1644                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1645        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1646    } else {
1647        MBEDTLS_SSL_DEBUG_MSG(1, ("got no ciphersuites in common"));
1648        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1649                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1650        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1651    }
1652
1653have_ciphersuite:
1654    MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %s", ciphersuite_info->name));
1655
1656    ssl->session_negotiate->ciphersuite = ciphersuites[i];
1657    ssl->handshake->ciphersuite_info = ciphersuite_info;
1658
1659    ssl->state++;
1660
1661#if defined(MBEDTLS_SSL_PROTO_DTLS)
1662    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1663        mbedtls_ssl_recv_flight_completed(ssl);
1664    }
1665#endif
1666
1667    /* Debugging-only output for testsuite */
1668#if defined(MBEDTLS_DEBUG_C)                         && \
1669    defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1670    mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg(ciphersuite_info);
1671    if (sig_alg != MBEDTLS_PK_NONE) {
1672        unsigned int sig_hash = mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
1673            ssl, mbedtls_ssl_sig_from_pk_alg(sig_alg));
1674        MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, signature_algorithm ext: %u",
1675                                  sig_hash));
1676    } else {
1677        MBEDTLS_SSL_DEBUG_MSG(3, ("no hash algorithm for signature algorithm "
1678                                  "%u - should not happen", (unsigned) sig_alg));
1679    }
1680#endif
1681
1682    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client hello"));
1683
1684    return 0;
1685}
1686
1687#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1688static void ssl_write_cid_ext(mbedtls_ssl_context *ssl,
1689                              unsigned char *buf,
1690                              size_t *olen)
1691{
1692    unsigned char *p = buf;
1693    size_t ext_len;
1694    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
1695
1696    *olen = 0;
1697
1698    /* Skip writing the extension if we don't want to use it or if
1699     * the client hasn't offered it. */
1700    if (ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED) {
1701        return;
1702    }
1703
1704    /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX
1705     * which is at most 255, so the increment cannot overflow. */
1706    if (end < p || (size_t) (end - p) < (unsigned) (ssl->own_cid_len + 5)) {
1707        MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
1708        return;
1709    }
1710
1711    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding CID extension"));
1712
1713    /*
1714     *   struct {
1715     *      opaque cid<0..2^8-1>;
1716     *   } ConnectionId;
1717     */
1718    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_CID, p, 0);
1719    p += 2;
1720    ext_len = (size_t) ssl->own_cid_len + 1;
1721    MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
1722    p += 2;
1723
1724    *p++ = (uint8_t) ssl->own_cid_len;
1725    memcpy(p, ssl->own_cid, ssl->own_cid_len);
1726
1727    *olen = ssl->own_cid_len + 5;
1728}
1729#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1730
1731#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
1732static void ssl_write_encrypt_then_mac_ext(mbedtls_ssl_context *ssl,
1733                                           unsigned char *buf,
1734                                           size_t *olen)
1735{
1736    unsigned char *p = buf;
1737    const mbedtls_ssl_ciphersuite_t *suite = NULL;
1738
1739    /*
1740     * RFC 7366: "If a server receives an encrypt-then-MAC request extension
1741     * from a client and then selects a stream or Authenticated Encryption
1742     * with Associated Data (AEAD) ciphersuite, it MUST NOT send an
1743     * encrypt-then-MAC response extension back to the client."
1744     */
1745    suite = mbedtls_ssl_ciphersuite_from_id(
1746        ssl->session_negotiate->ciphersuite);
1747    if (suite == NULL) {
1748        ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_DISABLED;
1749    } else {
1750        mbedtls_ssl_mode_t ssl_mode =
1751            mbedtls_ssl_get_mode_from_ciphersuite(
1752                ssl->session_negotiate->encrypt_then_mac,
1753                suite);
1754
1755        if (ssl_mode != MBEDTLS_SSL_MODE_CBC_ETM) {
1756            ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_DISABLED;
1757        }
1758    }
1759
1760    if (ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED) {
1761        *olen = 0;
1762        return;
1763    }
1764
1765    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding encrypt then mac extension"));
1766
1767    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC, p, 0);
1768    p += 2;
1769
1770    *p++ = 0x00;
1771    *p++ = 0x00;
1772
1773    *olen = 4;
1774}
1775#endif /* MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM */
1776
1777#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1778static void ssl_write_extended_ms_ext(mbedtls_ssl_context *ssl,
1779                                      unsigned char *buf,
1780                                      size_t *olen)
1781{
1782    unsigned char *p = buf;
1783
1784    if (ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED) {
1785        *olen = 0;
1786        return;
1787    }
1788
1789    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding extended master secret "
1790                              "extension"));
1791
1792    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET, p, 0);
1793    p += 2;
1794
1795    *p++ = 0x00;
1796    *p++ = 0x00;
1797
1798    *olen = 4;
1799}
1800#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1801
1802#if defined(MBEDTLS_SSL_SESSION_TICKETS)
1803static void ssl_write_session_ticket_ext(mbedtls_ssl_context *ssl,
1804                                         unsigned char *buf,
1805                                         size_t *olen)
1806{
1807    unsigned char *p = buf;
1808
1809    if (ssl->handshake->new_session_ticket == 0) {
1810        *olen = 0;
1811        return;
1812    }
1813
1814    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding session ticket extension"));
1815
1816    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SESSION_TICKET, p, 0);
1817    p += 2;
1818
1819    *p++ = 0x00;
1820    *p++ = 0x00;
1821
1822    *olen = 4;
1823}
1824#endif /* MBEDTLS_SSL_SESSION_TICKETS */
1825
1826static void ssl_write_renegotiation_ext(mbedtls_ssl_context *ssl,
1827                                        unsigned char *buf,
1828                                        size_t *olen)
1829{
1830    unsigned char *p = buf;
1831
1832    if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION) {
1833        *olen = 0;
1834        return;
1835    }
1836
1837    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, secure renegotiation extension"));
1838
1839    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_RENEGOTIATION_INFO, p, 0);
1840    p += 2;
1841
1842#if defined(MBEDTLS_SSL_RENEGOTIATION)
1843    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
1844        *p++ = 0x00;
1845        *p++ = (ssl->verify_data_len * 2 + 1) & 0xFF;
1846        *p++ = ssl->verify_data_len * 2 & 0xFF;
1847
1848        memcpy(p, ssl->peer_verify_data, ssl->verify_data_len);
1849        p += ssl->verify_data_len;
1850        memcpy(p, ssl->own_verify_data, ssl->verify_data_len);
1851        p += ssl->verify_data_len;
1852    } else
1853#endif /* MBEDTLS_SSL_RENEGOTIATION */
1854    {
1855        *p++ = 0x00;
1856        *p++ = 0x01;
1857        *p++ = 0x00;
1858    }
1859
1860    *olen = (size_t) (p - buf);
1861}
1862
1863#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1864static void ssl_write_max_fragment_length_ext(mbedtls_ssl_context *ssl,
1865                                              unsigned char *buf,
1866                                              size_t *olen)
1867{
1868    unsigned char *p = buf;
1869
1870    if (ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE) {
1871        *olen = 0;
1872        return;
1873    }
1874
1875    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, max_fragment_length extension"));
1876
1877    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH, p, 0);
1878    p += 2;
1879
1880    *p++ = 0x00;
1881    *p++ = 1;
1882
1883    *p++ = ssl->session_negotiate->mfl_code;
1884
1885    *olen = 5;
1886}
1887#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1888
1889#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
1890    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
1891    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1892static void ssl_write_supported_point_formats_ext(mbedtls_ssl_context *ssl,
1893                                                  unsigned char *buf,
1894                                                  size_t *olen)
1895{
1896    unsigned char *p = buf;
1897    ((void) ssl);
1898
1899    if ((ssl->handshake->cli_exts &
1900         MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT) == 0) {
1901        *olen = 0;
1902        return;
1903    }
1904
1905    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, supported_point_formats extension"));
1906
1907    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS, p, 0);
1908    p += 2;
1909
1910    *p++ = 0x00;
1911    *p++ = 2;
1912
1913    *p++ = 1;
1914    *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
1915
1916    *olen = 6;
1917}
1918#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED ||
1919          MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED ||
1920          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1921
1922#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1923static void ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
1924                                       unsigned char *buf,
1925                                       size_t *olen)
1926{
1927    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1928    unsigned char *p = buf;
1929    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
1930    size_t kkpp_len;
1931
1932    *olen = 0;
1933
1934    /* Skip costly computation if not needed */
1935    if (ssl->handshake->ciphersuite_info->key_exchange !=
1936        MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1937        return;
1938    }
1939
1940    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, ecjpake kkpp extension"));
1941
1942    if (end - p < 4) {
1943        MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
1944        return;
1945    }
1946
1947    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0);
1948    p += 2;
1949
1950#if defined(MBEDTLS_USE_PSA_CRYPTO)
1951    ret = mbedtls_psa_ecjpake_write_round(&ssl->handshake->psa_pake_ctx,
1952                                          p + 2, (size_t) (end - p - 2), &kkpp_len,
1953                                          MBEDTLS_ECJPAKE_ROUND_ONE);
1954    if (ret != 0) {
1955        psa_destroy_key(ssl->handshake->psa_pake_password);
1956        psa_pake_abort(&ssl->handshake->psa_pake_ctx);
1957        MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_output", ret);
1958        return;
1959    }
1960#else
1961    ret = mbedtls_ecjpake_write_round_one(&ssl->handshake->ecjpake_ctx,
1962                                          p + 2, (size_t) (end - p - 2), &kkpp_len,
1963                                          ssl->conf->f_rng, ssl->conf->p_rng);
1964    if (ret != 0) {
1965        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_one", ret);
1966        return;
1967    }
1968#endif /* MBEDTLS_USE_PSA_CRYPTO */
1969
1970    MBEDTLS_PUT_UINT16_BE(kkpp_len, p, 0);
1971    p += 2;
1972
1973    *olen = kkpp_len + 4;
1974}
1975#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1976
1977#if defined(MBEDTLS_SSL_DTLS_SRTP) && defined(MBEDTLS_SSL_PROTO_DTLS)
1978static void ssl_write_use_srtp_ext(mbedtls_ssl_context *ssl,
1979                                   unsigned char *buf,
1980                                   size_t *olen)
1981{
1982    size_t mki_len = 0, ext_len = 0;
1983    uint16_t profile_value = 0;
1984    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
1985
1986    *olen = 0;
1987
1988    if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
1989        (ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET)) {
1990        return;
1991    }
1992
1993    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding use_srtp extension"));
1994
1995    if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED) {
1996        mki_len = ssl->dtls_srtp_info.mki_len;
1997    }
1998
1999    /* The extension total size is 9 bytes :
2000     * - 2 bytes for the extension tag
2001     * - 2 bytes for the total size
2002     * - 2 bytes for the protection profile length
2003     * - 2 bytes for the protection profile
2004     * - 1 byte for the mki length
2005     * +  the actual mki length
2006     * Check we have enough room in the output buffer */
2007    if ((size_t) (end - buf) < mki_len + 9) {
2008        MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
2009        return;
2010    }
2011
2012    /* extension */
2013    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_USE_SRTP, buf, 0);
2014    /*
2015     * total length 5 and mki value: only one profile(2 bytes)
2016     *              and length(2 bytes) and srtp_mki  )
2017     */
2018    ext_len = 5 + mki_len;
2019    MBEDTLS_PUT_UINT16_BE(ext_len, buf, 2);
2020
2021    /* protection profile length: 2 */
2022    buf[4] = 0x00;
2023    buf[5] = 0x02;
2024    profile_value = mbedtls_ssl_check_srtp_profile_value(
2025        ssl->dtls_srtp_info.chosen_dtls_srtp_profile);
2026    if (profile_value != MBEDTLS_TLS_SRTP_UNSET) {
2027        MBEDTLS_PUT_UINT16_BE(profile_value, buf, 6);
2028    } else {
2029        MBEDTLS_SSL_DEBUG_MSG(1, ("use_srtp extension invalid profile"));
2030        return;
2031    }
2032
2033    buf[8] = mki_len & 0xFF;
2034    memcpy(&buf[9], ssl->dtls_srtp_info.mki_value, mki_len);
2035
2036    *olen = 9 + mki_len;
2037}
2038#endif /* MBEDTLS_SSL_DTLS_SRTP */
2039
2040#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2041MBEDTLS_CHECK_RETURN_CRITICAL
2042static int ssl_write_hello_verify_request(mbedtls_ssl_context *ssl)
2043{
2044    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2045    unsigned char *p = ssl->out_msg + 4;
2046    unsigned char *cookie_len_byte;
2047
2048    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write hello verify request"));
2049
2050    /*
2051     * struct {
2052     *   ProtocolVersion server_version;
2053     *   opaque cookie<0..2^8-1>;
2054     * } HelloVerifyRequest;
2055     */
2056
2057    /* The RFC is not clear on this point, but sending the actual negotiated
2058     * version looks like the most interoperable thing to do. */
2059    mbedtls_ssl_write_version(p, ssl->conf->transport, ssl->tls_version);
2060    MBEDTLS_SSL_DEBUG_BUF(3, "server version", p, 2);
2061    p += 2;
2062
2063    /* If we get here, f_cookie_check is not null */
2064    if (ssl->conf->f_cookie_write == NULL) {
2065        MBEDTLS_SSL_DEBUG_MSG(1, ("inconsistent cookie callbacks"));
2066        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2067    }
2068
2069    /* Skip length byte until we know the length */
2070    cookie_len_byte = p++;
2071
2072    if ((ret = ssl->conf->f_cookie_write(ssl->conf->p_cookie,
2073                                         &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,
2074                                         ssl->cli_id, ssl->cli_id_len)) != 0) {
2075        MBEDTLS_SSL_DEBUG_RET(1, "f_cookie_write", ret);
2076        return ret;
2077    }
2078
2079    *cookie_len_byte = (unsigned char) (p - (cookie_len_byte + 1));
2080
2081    MBEDTLS_SSL_DEBUG_BUF(3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte);
2082
2083    ssl->out_msglen  = (size_t) (p - ssl->out_msg);
2084    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2085    ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
2086
2087    ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
2088
2089    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
2090        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
2091        return ret;
2092    }
2093
2094#if defined(MBEDTLS_SSL_PROTO_DTLS)
2095    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2096        (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
2097        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
2098        return ret;
2099    }
2100#endif /* MBEDTLS_SSL_PROTO_DTLS */
2101
2102    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write hello verify request"));
2103
2104    return 0;
2105}
2106#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2107
2108static void ssl_handle_id_based_session_resumption(mbedtls_ssl_context *ssl)
2109{
2110    int ret;
2111    mbedtls_ssl_session session_tmp;
2112    mbedtls_ssl_session * const session = ssl->session_negotiate;
2113
2114    /* Resume is 0  by default, see ssl_handshake_init().
2115     * It may be already set to 1 by ssl_parse_session_ticket_ext(). */
2116    if (ssl->handshake->resume == 1) {
2117        return;
2118    }
2119    if (session->id_len == 0) {
2120        return;
2121    }
2122    if (ssl->conf->f_get_cache == NULL) {
2123        return;
2124    }
2125#if defined(MBEDTLS_SSL_RENEGOTIATION)
2126    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
2127        return;
2128    }
2129#endif
2130
2131    mbedtls_ssl_session_init(&session_tmp);
2132
2133    ret = ssl->conf->f_get_cache(ssl->conf->p_cache,
2134                                 session->id,
2135                                 session->id_len,
2136                                 &session_tmp);
2137    if (ret != 0) {
2138        goto exit;
2139    }
2140
2141    if (session->ciphersuite != session_tmp.ciphersuite) {
2142        /* Mismatch between cached and negotiated session */
2143        goto exit;
2144    }
2145
2146    /* Move semantics */
2147    mbedtls_ssl_session_free(session);
2148    *session = session_tmp;
2149    memset(&session_tmp, 0, sizeof(session_tmp));
2150
2151    MBEDTLS_SSL_DEBUG_MSG(3, ("session successfully restored from cache"));
2152    ssl->handshake->resume = 1;
2153
2154exit:
2155
2156    mbedtls_ssl_session_free(&session_tmp);
2157}
2158
2159MBEDTLS_CHECK_RETURN_CRITICAL
2160static int ssl_write_server_hello(mbedtls_ssl_context *ssl)
2161{
2162#if defined(MBEDTLS_HAVE_TIME)
2163    mbedtls_time_t t;
2164#endif
2165    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2166    size_t olen, ext_len = 0, n;
2167    unsigned char *buf, *p;
2168
2169    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello"));
2170
2171#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2172    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2173        ssl->handshake->cookie_verify_result != 0) {
2174        MBEDTLS_SSL_DEBUG_MSG(2, ("client hello was not authenticated"));
2175        MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2176
2177        return ssl_write_hello_verify_request(ssl);
2178    }
2179#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2180
2181    /*
2182     *     0  .   0   handshake type
2183     *     1  .   3   handshake length
2184     *     4  .   5   protocol version
2185     *     6  .   9   UNIX time()
2186     *    10  .  37   random bytes
2187     */
2188    buf = ssl->out_msg;
2189    p = buf + 4;
2190
2191    mbedtls_ssl_write_version(p, ssl->conf->transport, ssl->tls_version);
2192    p += 2;
2193
2194    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen version: [%d:%d]",
2195                              buf[4], buf[5]));
2196
2197#if defined(MBEDTLS_HAVE_TIME)
2198    t = mbedtls_time(NULL);
2199    MBEDTLS_PUT_UINT32_BE(t, p, 0);
2200    p += 4;
2201
2202    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, current time: %" MBEDTLS_PRINTF_LONGLONG,
2203                              (long long) t));
2204#else
2205    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 4)) != 0) {
2206        return ret;
2207    }
2208
2209    p += 4;
2210#endif /* MBEDTLS_HAVE_TIME */
2211
2212    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 20)) != 0) {
2213        return ret;
2214    }
2215    p += 20;
2216
2217#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
2218    /*
2219     * RFC 8446
2220     * TLS 1.3 has a downgrade protection mechanism embedded in the server's
2221     * random value. TLS 1.3 servers which negotiate TLS 1.2 or below in
2222     * response to a ClientHello MUST set the last 8 bytes of their Random
2223     * value specially in their ServerHello.
2224     */
2225    if (mbedtls_ssl_conf_is_tls13_enabled(ssl->conf)) {
2226        static const unsigned char magic_tls12_downgrade_string[] =
2227        { 'D', 'O', 'W', 'N', 'G', 'R', 'D', 1 };
2228
2229        MBEDTLS_STATIC_ASSERT(
2230            sizeof(magic_tls12_downgrade_string) == 8,
2231            "magic_tls12_downgrade_string does not have the expected size");
2232
2233        memcpy(p, magic_tls12_downgrade_string,
2234               sizeof(magic_tls12_downgrade_string));
2235    } else
2236#endif
2237    {
2238        if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 8)) != 0) {
2239            return ret;
2240        }
2241    }
2242    p += 8;
2243
2244    memcpy(ssl->handshake->randbytes + 32, buf + 6, 32);
2245
2246    MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes", buf + 6, 32);
2247
2248    ssl_handle_id_based_session_resumption(ssl);
2249
2250    if (ssl->handshake->resume == 0) {
2251        /*
2252         * New session, create a new session id,
2253         * unless we're about to issue a session ticket
2254         */
2255        ssl->state++;
2256
2257#if defined(MBEDTLS_HAVE_TIME)
2258        ssl->session_negotiate->start = mbedtls_time(NULL);
2259#endif
2260
2261#if defined(MBEDTLS_SSL_SESSION_TICKETS)
2262        if (ssl->handshake->new_session_ticket != 0) {
2263            ssl->session_negotiate->id_len = n = 0;
2264            memset(ssl->session_negotiate->id, 0, 32);
2265        } else
2266#endif /* MBEDTLS_SSL_SESSION_TICKETS */
2267        {
2268            ssl->session_negotiate->id_len = n = 32;
2269            if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, ssl->session_negotiate->id,
2270                                        n)) != 0) {
2271                return ret;
2272            }
2273        }
2274    } else {
2275        /*
2276         * Resuming a session
2277         */
2278        n = ssl->session_negotiate->id_len;
2279        ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
2280
2281        if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
2282            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
2283            return ret;
2284        }
2285    }
2286
2287    /*
2288     *    38  .  38     session id length
2289     *    39  . 38+n    session id
2290     *   39+n . 40+n    chosen ciphersuite
2291     *   41+n . 41+n    chosen compression alg.
2292     *   42+n . 43+n    extensions length
2293     *   44+n . 43+n+m  extensions
2294     */
2295    *p++ = (unsigned char) ssl->session_negotiate->id_len;
2296    memcpy(p, ssl->session_negotiate->id, ssl->session_negotiate->id_len);
2297    p += ssl->session_negotiate->id_len;
2298
2299    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n));
2300    MBEDTLS_SSL_DEBUG_BUF(3,   "server hello, session id", buf + 39, n);
2301    MBEDTLS_SSL_DEBUG_MSG(3, ("%s session has been resumed",
2302                              ssl->handshake->resume ? "a" : "no"));
2303
2304    MBEDTLS_PUT_UINT16_BE(ssl->session_negotiate->ciphersuite, p, 0);
2305    p += 2;
2306    *p++ = MBEDTLS_BYTE_0(MBEDTLS_SSL_COMPRESS_NULL);
2307
2308    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen ciphersuite: %s",
2309                              mbedtls_ssl_get_ciphersuite_name(ssl->session_negotiate->ciphersuite)));
2310    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, compress alg.: 0x%02X",
2311                              (unsigned int) MBEDTLS_SSL_COMPRESS_NULL));
2312
2313    /*
2314     *  First write extensions, then the total length
2315     */
2316    ssl_write_renegotiation_ext(ssl, p + 2 + ext_len, &olen);
2317    ext_len += olen;
2318
2319#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2320    ssl_write_max_fragment_length_ext(ssl, p + 2 + ext_len, &olen);
2321    ext_len += olen;
2322#endif
2323
2324#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2325    ssl_write_cid_ext(ssl, p + 2 + ext_len, &olen);
2326    ext_len += olen;
2327#endif
2328
2329#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2330    ssl_write_encrypt_then_mac_ext(ssl, p + 2 + ext_len, &olen);
2331    ext_len += olen;
2332#endif
2333
2334#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2335    ssl_write_extended_ms_ext(ssl, p + 2 + ext_len, &olen);
2336    ext_len += olen;
2337#endif
2338
2339#if defined(MBEDTLS_SSL_SESSION_TICKETS)
2340    ssl_write_session_ticket_ext(ssl, p + 2 + ext_len, &olen);
2341    ext_len += olen;
2342#endif
2343
2344#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
2345    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
2346    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2347    const mbedtls_ssl_ciphersuite_t *suite =
2348        mbedtls_ssl_ciphersuite_from_id(ssl->session_negotiate->ciphersuite);
2349    if (suite != NULL && mbedtls_ssl_ciphersuite_uses_ec(suite)) {
2350        ssl_write_supported_point_formats_ext(ssl, p + 2 + ext_len, &olen);
2351        ext_len += olen;
2352    }
2353#endif
2354
2355#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2356    ssl_write_ecjpake_kkpp_ext(ssl, p + 2 + ext_len, &olen);
2357    ext_len += olen;
2358#endif
2359
2360#if defined(MBEDTLS_SSL_ALPN)
2361    unsigned char *end = buf + MBEDTLS_SSL_OUT_CONTENT_LEN - 4;
2362    if ((ret = mbedtls_ssl_write_alpn_ext(ssl, p + 2 + ext_len, end, &olen))
2363        != 0) {
2364        return ret;
2365    }
2366
2367    ext_len += olen;
2368#endif
2369
2370#if defined(MBEDTLS_SSL_DTLS_SRTP)
2371    ssl_write_use_srtp_ext(ssl, p + 2 + ext_len, &olen);
2372    ext_len += olen;
2373#endif
2374
2375    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, total extension length: %" MBEDTLS_PRINTF_SIZET,
2376                              ext_len));
2377
2378    if (ext_len > 0) {
2379        MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
2380        p += 2 + ext_len;
2381    }
2382
2383    ssl->out_msglen  = (size_t) (p - buf);
2384    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2385    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;
2386
2387    ret = mbedtls_ssl_write_handshake_msg(ssl);
2388
2389    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2390
2391    return ret;
2392}
2393
2394#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
2395MBEDTLS_CHECK_RETURN_CRITICAL
2396static int ssl_write_certificate_request(mbedtls_ssl_context *ssl)
2397{
2398    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2399        ssl->handshake->ciphersuite_info;
2400
2401    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2402
2403    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
2404        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
2405        ssl->state++;
2406        return 0;
2407    }
2408
2409    MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2410    return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2411}
2412#else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
2413MBEDTLS_CHECK_RETURN_CRITICAL
2414static int ssl_write_certificate_request(mbedtls_ssl_context *ssl)
2415{
2416    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2417    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2418        ssl->handshake->ciphersuite_info;
2419    uint16_t dn_size, total_dn_size; /* excluding length bytes */
2420    size_t ct_len, sa_len; /* including length bytes */
2421    unsigned char *buf, *p;
2422    const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2423    const mbedtls_x509_crt *crt;
2424    int authmode;
2425
2426    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2427
2428    ssl->state++;
2429
2430#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2431    if (ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET) {
2432        authmode = ssl->handshake->sni_authmode;
2433    } else
2434#endif
2435    authmode = ssl->conf->authmode;
2436
2437    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info) ||
2438        authmode == MBEDTLS_SSL_VERIFY_NONE) {
2439        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
2440        return 0;
2441    }
2442
2443    /*
2444     *     0  .   0   handshake type
2445     *     1  .   3   handshake length
2446     *     4  .   4   cert type count
2447     *     5  .. m-1  cert types
2448     *     m  .. m+1  sig alg length (TLS 1.2 only)
2449     *    m+1 .. n-1  SignatureAndHashAlgorithms (TLS 1.2 only)
2450     *     n  .. n+1  length of all DNs
2451     *    n+2 .. n+3  length of DN 1
2452     *    n+4 .. ...  Distinguished Name #1
2453     *    ... .. ...  length of DN 2, etc.
2454     */
2455    buf = ssl->out_msg;
2456    p = buf + 4;
2457
2458    /*
2459     * Supported certificate types
2460     *
2461     *     ClientCertificateType certificate_types<1..2^8-1>;
2462     *     enum { (255) } ClientCertificateType;
2463     */
2464    ct_len = 0;
2465
2466#if defined(MBEDTLS_RSA_C)
2467    p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
2468#endif
2469#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
2470    p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;
2471#endif
2472
2473    p[0] = (unsigned char) ct_len++;
2474    p += ct_len;
2475
2476    sa_len = 0;
2477
2478    /*
2479     * Add signature_algorithms for verify (TLS 1.2)
2480     *
2481     *     SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>;
2482     *
2483     *     struct {
2484     *           HashAlgorithm hash;
2485     *           SignatureAlgorithm signature;
2486     *     } SignatureAndHashAlgorithm;
2487     *
2488     *     enum { (255) } HashAlgorithm;
2489     *     enum { (255) } SignatureAlgorithm;
2490     */
2491    const uint16_t *sig_alg = mbedtls_ssl_get_sig_algs(ssl);
2492    if (sig_alg == NULL) {
2493        return MBEDTLS_ERR_SSL_BAD_CONFIG;
2494    }
2495
2496    for (; *sig_alg != MBEDTLS_TLS_SIG_NONE; sig_alg++) {
2497        unsigned char hash = MBEDTLS_BYTE_1(*sig_alg);
2498
2499        if (mbedtls_ssl_set_calc_verify_md(ssl, hash)) {
2500            continue;
2501        }
2502        if (!mbedtls_ssl_sig_alg_is_supported(ssl, *sig_alg)) {
2503            continue;
2504        }
2505
2506        /* Write elements at offsets starting from 1 (offset 0 is for the
2507         * length). Thus the offset of each element is the length of the
2508         * partial list including that element. */
2509        sa_len += 2;
2510        MBEDTLS_PUT_UINT16_BE(*sig_alg, p, sa_len);
2511
2512    }
2513
2514    /* Fill in list length. */
2515    MBEDTLS_PUT_UINT16_BE(sa_len, p, 0);
2516    sa_len += 2;
2517    p += sa_len;
2518
2519    /*
2520     * DistinguishedName certificate_authorities<0..2^16-1>;
2521     * opaque DistinguishedName<1..2^16-1>;
2522     */
2523    p += 2;
2524
2525    total_dn_size = 0;
2526
2527    if (ssl->conf->cert_req_ca_list ==  MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED) {
2528        /* NOTE: If trusted certificates are provisioned
2529         *       via a CA callback (configured through
2530         *       `mbedtls_ssl_conf_ca_cb()`, then the
2531         *       CertificateRequest is currently left empty. */
2532
2533#if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
2534#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2535        if (ssl->handshake->dn_hints != NULL) {
2536            crt = ssl->handshake->dn_hints;
2537        } else
2538#endif
2539        if (ssl->conf->dn_hints != NULL) {
2540            crt = ssl->conf->dn_hints;
2541        } else
2542#endif
2543#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2544        if (ssl->handshake->sni_ca_chain != NULL) {
2545            crt = ssl->handshake->sni_ca_chain;
2546        } else
2547#endif
2548        crt = ssl->conf->ca_chain;
2549
2550        while (crt != NULL && crt->version != 0) {
2551            /* It follows from RFC 5280 A.1 that this length
2552             * can be represented in at most 11 bits. */
2553            dn_size = (uint16_t) crt->subject_raw.len;
2554
2555            if (end < p || (size_t) (end - p) < 2 + (size_t) dn_size) {
2556                MBEDTLS_SSL_DEBUG_MSG(1, ("skipping CAs: buffer too short"));
2557                break;
2558            }
2559
2560            MBEDTLS_PUT_UINT16_BE(dn_size, p, 0);
2561            p += 2;
2562            memcpy(p, crt->subject_raw.p, dn_size);
2563            p += dn_size;
2564
2565            MBEDTLS_SSL_DEBUG_BUF(3, "requested DN", p - dn_size, dn_size);
2566
2567            total_dn_size += (unsigned short) (2 + dn_size);
2568            crt = crt->next;
2569        }
2570    }
2571
2572    ssl->out_msglen  = (size_t) (p - buf);
2573    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2574    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;
2575    MBEDTLS_PUT_UINT16_BE(total_dn_size, ssl->out_msg, 4 + ct_len + sa_len);
2576
2577    ret = mbedtls_ssl_write_handshake_msg(ssl);
2578
2579    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate request"));
2580
2581    return ret;
2582}
2583#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
2584
2585#if (defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
2586    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED))
2587#if defined(MBEDTLS_USE_PSA_CRYPTO)
2588MBEDTLS_CHECK_RETURN_CRITICAL
2589static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
2590{
2591    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2592    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2593    mbedtls_pk_context *pk;
2594    mbedtls_pk_type_t pk_type;
2595    psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
2596    unsigned char buf[PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)];
2597    size_t key_len;
2598#if !defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2599    uint16_t tls_id = 0;
2600    psa_key_type_t key_type = PSA_KEY_TYPE_NONE;
2601    mbedtls_ecp_group_id grp_id;
2602    mbedtls_ecp_keypair *key;
2603#endif /* !MBEDTLS_PK_USE_PSA_EC_DATA */
2604
2605    pk = mbedtls_ssl_own_key(ssl);
2606
2607    if (pk == NULL) {
2608        return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2609    }
2610
2611    pk_type = mbedtls_pk_get_type(pk);
2612
2613    switch (pk_type) {
2614        case MBEDTLS_PK_OPAQUE:
2615#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2616        case MBEDTLS_PK_ECKEY:
2617        case MBEDTLS_PK_ECKEY_DH:
2618        case MBEDTLS_PK_ECDSA:
2619#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
2620            if (!mbedtls_pk_can_do(pk, MBEDTLS_PK_ECKEY)) {
2621                return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2622            }
2623
2624            /* Get the attributes of the key previously parsed by PK module in
2625             * order to extract its type and length (in bits). */
2626            status = psa_get_key_attributes(pk->priv_id, &key_attributes);
2627            if (status != PSA_SUCCESS) {
2628                ret = PSA_TO_MBEDTLS_ERR(status);
2629                goto exit;
2630            }
2631            ssl->handshake->xxdh_psa_type = psa_get_key_type(&key_attributes);
2632            ssl->handshake->xxdh_psa_bits = psa_get_key_bits(&key_attributes);
2633
2634            if (pk_type == MBEDTLS_PK_OPAQUE) {
2635                /* Opaque key is created by the user (externally from Mbed TLS)
2636                 * so we assume it already has the right algorithm and flags
2637                 * set. Just copy its ID as reference. */
2638                ssl->handshake->xxdh_psa_privkey = pk->priv_id;
2639                ssl->handshake->xxdh_psa_privkey_is_external = 1;
2640            } else {
2641                /* PK_ECKEY[_DH] and PK_ECDSA instead as parsed from the PK
2642                 * module and only have ECDSA capabilities. Since we need
2643                 * them for ECDH later, we export and then re-import them with
2644                 * proper flags and algorithm. Of course We also set key's type
2645                 * and bits that we just got above. */
2646                key_attributes = psa_key_attributes_init();
2647                psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
2648                psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
2649                psa_set_key_type(&key_attributes,
2650                                 PSA_KEY_TYPE_ECC_KEY_PAIR(ssl->handshake->xxdh_psa_type));
2651                psa_set_key_bits(&key_attributes, ssl->handshake->xxdh_psa_bits);
2652
2653                status = psa_export_key(pk->priv_id, buf, sizeof(buf), &key_len);
2654                if (status != PSA_SUCCESS) {
2655                    ret = PSA_TO_MBEDTLS_ERR(status);
2656                    goto exit;
2657                }
2658                status = psa_import_key(&key_attributes, buf, key_len,
2659                                        &ssl->handshake->xxdh_psa_privkey);
2660                if (status != PSA_SUCCESS) {
2661                    ret = PSA_TO_MBEDTLS_ERR(status);
2662                    goto exit;
2663                }
2664
2665                /* Set this key as owned by the TLS library: it will be its duty
2666                 * to clear it exit. */
2667                ssl->handshake->xxdh_psa_privkey_is_external = 0;
2668            }
2669
2670            ret = 0;
2671            break;
2672#if !defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2673        case MBEDTLS_PK_ECKEY:
2674        case MBEDTLS_PK_ECKEY_DH:
2675        case MBEDTLS_PK_ECDSA:
2676            key = mbedtls_pk_ec_rw(*pk);
2677            grp_id = mbedtls_pk_get_ec_group_id(pk);
2678            if (grp_id == MBEDTLS_ECP_DP_NONE) {
2679                return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2680            }
2681            tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(grp_id);
2682            if (tls_id == 0) {
2683                /* This elliptic curve is not supported */
2684                return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2685            }
2686
2687            /* If the above conversion to TLS ID was fine, then also this one will
2688               be, so there is no need to check the return value here */
2689            mbedtls_ssl_get_psa_curve_info_from_tls_id(tls_id, &key_type,
2690                                                       &ssl->handshake->xxdh_psa_bits);
2691
2692            ssl->handshake->xxdh_psa_type = key_type;
2693
2694            key_attributes = psa_key_attributes_init();
2695            psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
2696            psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
2697            psa_set_key_type(&key_attributes,
2698                             PSA_KEY_TYPE_ECC_KEY_PAIR(ssl->handshake->xxdh_psa_type));
2699            psa_set_key_bits(&key_attributes, ssl->handshake->xxdh_psa_bits);
2700
2701            ret = mbedtls_ecp_write_key_ext(key, &key_len, buf, sizeof(buf));
2702            if (ret != 0) {
2703                mbedtls_platform_zeroize(buf, sizeof(buf));
2704                break;
2705            }
2706
2707            status = psa_import_key(&key_attributes, buf, key_len,
2708                                    &ssl->handshake->xxdh_psa_privkey);
2709            if (status != PSA_SUCCESS) {
2710                ret = PSA_TO_MBEDTLS_ERR(status);
2711                mbedtls_platform_zeroize(buf, sizeof(buf));
2712                break;
2713            }
2714
2715            mbedtls_platform_zeroize(buf, sizeof(buf));
2716            ret = 0;
2717            break;
2718#endif /* !MBEDTLS_PK_USE_PSA_EC_DATA */
2719        default:
2720            ret = MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2721    }
2722
2723exit:
2724    psa_reset_key_attributes(&key_attributes);
2725    mbedtls_platform_zeroize(buf, sizeof(buf));
2726
2727    return ret;
2728}
2729#else /* MBEDTLS_USE_PSA_CRYPTO */
2730MBEDTLS_CHECK_RETURN_CRITICAL
2731static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
2732{
2733    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2734
2735    const mbedtls_pk_context *private_key = mbedtls_ssl_own_key(ssl);
2736    if (private_key == NULL) {
2737        MBEDTLS_SSL_DEBUG_MSG(1, ("got no server private key"));
2738        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
2739    }
2740
2741    if (!mbedtls_pk_can_do(private_key, MBEDTLS_PK_ECKEY)) {
2742        MBEDTLS_SSL_DEBUG_MSG(1, ("server key not ECDH capable"));
2743        return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2744    }
2745
2746    if ((ret = mbedtls_ecdh_get_params(&ssl->handshake->ecdh_ctx,
2747                                       mbedtls_pk_ec_ro(*mbedtls_ssl_own_key(ssl)),
2748                                       MBEDTLS_ECDH_OURS)) != 0) {
2749        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ecdh_get_params"), ret);
2750        return ret;
2751    }
2752
2753    return 0;
2754}
2755#endif /* MBEDTLS_USE_PSA_CRYPTO */
2756#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
2757          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2758
2759#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
2760    defined(MBEDTLS_SSL_ASYNC_PRIVATE)
2761MBEDTLS_CHECK_RETURN_CRITICAL
2762static int ssl_resume_server_key_exchange(mbedtls_ssl_context *ssl,
2763                                          size_t *signature_len)
2764{
2765    /* Append the signature to ssl->out_msg, leaving 2 bytes for the
2766     * signature length which will be added in ssl_write_server_key_exchange
2767     * after the call to ssl_prepare_server_key_exchange.
2768     * ssl_write_server_key_exchange also takes care of incrementing
2769     * ssl->out_msglen. */
2770    unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;
2771    size_t sig_max_len = (ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN
2772                          - sig_start);
2773    int ret = ssl->conf->f_async_resume(ssl,
2774                                        sig_start, signature_len, sig_max_len);
2775    if (ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
2776        ssl->handshake->async_in_progress = 0;
2777        mbedtls_ssl_set_async_operation_data(ssl, NULL);
2778    }
2779    MBEDTLS_SSL_DEBUG_RET(2, "ssl_resume_server_key_exchange", ret);
2780    return ret;
2781}
2782#endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
2783          defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
2784
2785/* Prepare the ServerKeyExchange message, up to and including
2786 * calculating the signature if any, but excluding formatting the
2787 * signature and sending the message. */
2788MBEDTLS_CHECK_RETURN_CRITICAL
2789static int ssl_prepare_server_key_exchange(mbedtls_ssl_context *ssl,
2790                                           size_t *signature_len)
2791{
2792    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2793        ssl->handshake->ciphersuite_info;
2794
2795#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED)
2796#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2797    unsigned char *dig_signed = NULL;
2798#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
2799#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */
2800
2801    (void) ciphersuite_info; /* unused in some configurations */
2802#if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2803    (void) signature_len;
2804#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
2805
2806#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2807#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2808    size_t out_buf_len = ssl->out_buf_len - (size_t) (ssl->out_msg - ssl->out_buf);
2809#else
2810    size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN - (size_t) (ssl->out_msg - ssl->out_buf);
2811#endif
2812#endif
2813
2814    ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */
2815
2816    /*
2817     *
2818     * Part 1: Provide key exchange parameters for chosen ciphersuite.
2819     *
2820     */
2821
2822    /*
2823     * - ECJPAKE key exchanges
2824     */
2825#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2826    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
2827        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2828#if defined(MBEDTLS_USE_PSA_CRYPTO)
2829        unsigned char *out_p = ssl->out_msg + ssl->out_msglen;
2830        unsigned char *end_p = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN -
2831                               ssl->out_msglen;
2832        size_t output_offset = 0;
2833        size_t output_len = 0;
2834
2835        /*
2836         * The first 3 bytes are:
2837         * [0] MBEDTLS_ECP_TLS_NAMED_CURVE
2838         * [1, 2] elliptic curve's TLS ID
2839         *
2840         * However since we only support secp256r1 for now, we hardcode its
2841         * TLS ID here
2842         */
2843        uint16_t tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(
2844            MBEDTLS_ECP_DP_SECP256R1);
2845        if (tls_id == 0) {
2846            return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2847        }
2848        *out_p = MBEDTLS_ECP_TLS_NAMED_CURVE;
2849        MBEDTLS_PUT_UINT16_BE(tls_id, out_p, 1);
2850        output_offset += 3;
2851
2852        ret = mbedtls_psa_ecjpake_write_round(&ssl->handshake->psa_pake_ctx,
2853                                              out_p + output_offset,
2854                                              end_p - out_p - output_offset, &output_len,
2855                                              MBEDTLS_ECJPAKE_ROUND_TWO);
2856        if (ret != 0) {
2857            psa_destroy_key(ssl->handshake->psa_pake_password);
2858            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
2859            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_output", ret);
2860            return ret;
2861        }
2862
2863        output_offset += output_len;
2864        ssl->out_msglen += output_offset;
2865#else
2866        size_t len = 0;
2867
2868        ret = mbedtls_ecjpake_write_round_two(
2869            &ssl->handshake->ecjpake_ctx,
2870            ssl->out_msg + ssl->out_msglen,
2871            MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
2872            ssl->conf->f_rng, ssl->conf->p_rng);
2873        if (ret != 0) {
2874            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_two", ret);
2875            return ret;
2876        }
2877
2878        ssl->out_msglen += len;
2879#endif /* MBEDTLS_USE_PSA_CRYPTO */
2880    }
2881#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2882
2883    /*
2884     * For (EC)DHE key exchanges with PSK, parameters are prefixed by support
2885     * identity hint (RFC 4279, Sec. 3). Until someone needs this feature,
2886     * we use empty support identity hints here.
2887     **/
2888#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)   || \
2889    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
2890    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2891        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
2892        ssl->out_msg[ssl->out_msglen++] = 0x00;
2893        ssl->out_msg[ssl->out_msglen++] = 0x00;
2894    }
2895#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||
2896          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
2897
2898    /*
2899     * - DHE key exchanges
2900     */
2901#if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED)
2902    if (mbedtls_ssl_ciphersuite_uses_dhe(ciphersuite_info)) {
2903        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2904        size_t len = 0;
2905
2906        if (ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL) {
2907            MBEDTLS_SSL_DEBUG_MSG(1, ("no DH parameters set"));
2908            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2909        }
2910
2911        /*
2912         * Ephemeral DH parameters:
2913         *
2914         * struct {
2915         *     opaque dh_p<1..2^16-1>;
2916         *     opaque dh_g<1..2^16-1>;
2917         *     opaque dh_Ys<1..2^16-1>;
2918         * } ServerDHParams;
2919         */
2920        if ((ret = mbedtls_dhm_set_group(&ssl->handshake->dhm_ctx,
2921                                         &ssl->conf->dhm_P,
2922                                         &ssl->conf->dhm_G)) != 0) {
2923            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_set_group", ret);
2924            return ret;
2925        }
2926
2927        if ((ret = mbedtls_dhm_make_params(
2928                 &ssl->handshake->dhm_ctx,
2929                 (int) mbedtls_dhm_get_len(&ssl->handshake->dhm_ctx),
2930                 ssl->out_msg + ssl->out_msglen, &len,
2931                 ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2932            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_make_params", ret);
2933            return ret;
2934        }
2935
2936#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2937        dig_signed = ssl->out_msg + ssl->out_msglen;
2938#endif
2939
2940        ssl->out_msglen += len;
2941
2942        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: X ", &ssl->handshake->dhm_ctx.X);
2943        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: P ", &ssl->handshake->dhm_ctx.P);
2944        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: G ", &ssl->handshake->dhm_ctx.G);
2945        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GX", &ssl->handshake->dhm_ctx.GX);
2946    }
2947#endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */
2948
2949    /*
2950     * - ECDHE key exchanges
2951     */
2952#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
2953    if (mbedtls_ssl_ciphersuite_uses_ecdhe(ciphersuite_info)) {
2954        /*
2955         * Ephemeral ECDH parameters:
2956         *
2957         * struct {
2958         *     ECParameters curve_params;
2959         *     ECPoint      public;
2960         * } ServerECDHParams;
2961         */
2962        uint16_t *curr_tls_id = ssl->handshake->curves_tls_id;
2963        const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
2964        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2965        size_t len = 0;
2966
2967        /* Match our preference list against the offered curves */
2968        if ((group_list == NULL) || (curr_tls_id == NULL)) {
2969            return MBEDTLS_ERR_SSL_BAD_CONFIG;
2970        }
2971        for (; *group_list != 0; group_list++) {
2972            for (curr_tls_id = ssl->handshake->curves_tls_id;
2973                 *curr_tls_id != 0; curr_tls_id++) {
2974                if (*curr_tls_id == *group_list) {
2975                    goto curve_matching_done;
2976                }
2977            }
2978        }
2979
2980curve_matching_done:
2981        if (*curr_tls_id == 0) {
2982            MBEDTLS_SSL_DEBUG_MSG(1, ("no matching curve for ECDHE"));
2983            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2984        }
2985
2986        MBEDTLS_SSL_DEBUG_MSG(2, ("ECDHE curve: %s",
2987                                  mbedtls_ssl_get_curve_name_from_tls_id(*curr_tls_id)));
2988
2989#if defined(MBEDTLS_USE_PSA_CRYPTO)
2990        psa_status_t status = PSA_ERROR_GENERIC_ERROR;
2991        psa_key_attributes_t key_attributes;
2992        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2993        uint8_t *p = ssl->out_msg + ssl->out_msglen;
2994        const size_t header_size = 4; // curve_type(1), namedcurve(2),
2995                                      // data length(1)
2996        const size_t data_length_size = 1;
2997        psa_key_type_t key_type = PSA_KEY_TYPE_NONE;
2998        size_t ec_bits = 0;
2999
3000        MBEDTLS_SSL_DEBUG_MSG(1, ("Perform PSA-based ECDH computation."));
3001
3002        /* Convert EC's TLS ID to PSA key type. */
3003        if (mbedtls_ssl_get_psa_curve_info_from_tls_id(*curr_tls_id,
3004                                                       &key_type,
3005                                                       &ec_bits) == PSA_ERROR_NOT_SUPPORTED) {
3006            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid ecc group parse."));
3007            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
3008        }
3009        handshake->xxdh_psa_type = key_type;
3010        handshake->xxdh_psa_bits = ec_bits;
3011
3012        key_attributes = psa_key_attributes_init();
3013        psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
3014        psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
3015        psa_set_key_type(&key_attributes, handshake->xxdh_psa_type);
3016        psa_set_key_bits(&key_attributes, handshake->xxdh_psa_bits);
3017
3018        /*
3019         * ECParameters curve_params
3020         *
3021         * First byte is curve_type, always named_curve
3022         */
3023        *p++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
3024
3025        /*
3026         * Next two bytes are the namedcurve value
3027         */
3028        MBEDTLS_PUT_UINT16_BE(*curr_tls_id, p, 0);
3029        p += 2;
3030
3031        /* Generate ECDH private key. */
3032        status = psa_generate_key(&key_attributes,
3033                                  &handshake->xxdh_psa_privkey);
3034        if (status != PSA_SUCCESS) {
3035            ret = PSA_TO_MBEDTLS_ERR(status);
3036            MBEDTLS_SSL_DEBUG_RET(1, "psa_generate_key", ret);
3037            return ret;
3038        }
3039
3040        /*
3041         * ECPoint  public
3042         *
3043         * First byte is data length.
3044         * It will be filled later. p holds now the data length location.
3045         */
3046
3047        /* Export the public part of the ECDH private key from PSA.
3048         * Make one byte space for the length.
3049         */
3050        unsigned char *own_pubkey = p + data_length_size;
3051
3052        size_t own_pubkey_max_len = (size_t) (MBEDTLS_SSL_OUT_CONTENT_LEN
3053                                              - (own_pubkey - ssl->out_msg));
3054
3055        status = psa_export_public_key(handshake->xxdh_psa_privkey,
3056                                       own_pubkey, own_pubkey_max_len,
3057                                       &len);
3058        if (status != PSA_SUCCESS) {
3059            ret = PSA_TO_MBEDTLS_ERR(status);
3060            MBEDTLS_SSL_DEBUG_RET(1, "psa_export_public_key", ret);
3061            (void) psa_destroy_key(handshake->xxdh_psa_privkey);
3062            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3063            return ret;
3064        }
3065
3066        /* Store the length of the exported public key. */
3067        *p = (uint8_t) len;
3068
3069        /* Determine full message length. */
3070        len += header_size;
3071#else
3072        mbedtls_ecp_group_id curr_grp_id =
3073            mbedtls_ssl_get_ecp_group_id_from_tls_id(*curr_tls_id);
3074
3075        if ((ret = mbedtls_ecdh_setup(&ssl->handshake->ecdh_ctx,
3076                                      curr_grp_id)) != 0) {
3077            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecp_group_load", ret);
3078            return ret;
3079        }
3080
3081        if ((ret = mbedtls_ecdh_make_params(
3082                 &ssl->handshake->ecdh_ctx, &len,
3083                 ssl->out_msg + ssl->out_msglen,
3084                 MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
3085                 ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3086            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_make_params", ret);
3087            return ret;
3088        }
3089
3090        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3091                               MBEDTLS_DEBUG_ECDH_Q);
3092#endif /* MBEDTLS_USE_PSA_CRYPTO */
3093
3094#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3095        dig_signed = ssl->out_msg + ssl->out_msglen;
3096#endif
3097
3098        ssl->out_msglen += len;
3099    }
3100#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */
3101
3102    /*
3103     *
3104     * Part 2: For key exchanges involving the server signing the
3105     *         exchange parameters, compute and add the signature here.
3106     *
3107     */
3108#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3109    if (mbedtls_ssl_ciphersuite_uses_server_signature(ciphersuite_info)) {
3110        if (dig_signed == NULL) {
3111            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3112            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3113        }
3114
3115        size_t dig_signed_len = (size_t) (ssl->out_msg + ssl->out_msglen - dig_signed);
3116        size_t hashlen = 0;
3117        unsigned char hash[MBEDTLS_MD_MAX_SIZE];
3118
3119        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3120
3121        /*
3122         * 2.1: Choose hash algorithm:
3123         *      For TLS 1.2, obey signature-hash-algorithm extension
3124         *      to choose appropriate hash.
3125         */
3126
3127        mbedtls_pk_type_t sig_alg =
3128            mbedtls_ssl_get_ciphersuite_sig_pk_alg(ciphersuite_info);
3129
3130        unsigned char sig_hash =
3131            (unsigned char) mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
3132                ssl, mbedtls_ssl_sig_from_pk_alg(sig_alg));
3133
3134        mbedtls_md_type_t md_alg = mbedtls_ssl_md_alg_from_hash(sig_hash);
3135
3136        /*    For TLS 1.2, obey signature-hash-algorithm extension
3137         *    (RFC 5246, Sec. 7.4.1.4.1). */
3138        if (sig_alg == MBEDTLS_PK_NONE || md_alg == MBEDTLS_MD_NONE) {
3139            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3140            /* (... because we choose a cipher suite
3141             *      only if there is a matching hash.) */
3142            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3143        }
3144
3145        MBEDTLS_SSL_DEBUG_MSG(3, ("pick hash algorithm %u for signing", (unsigned) md_alg));
3146
3147        /*
3148         * 2.2: Compute the hash to be signed
3149         */
3150        if (md_alg != MBEDTLS_MD_NONE) {
3151            ret = mbedtls_ssl_get_key_exchange_md_tls1_2(ssl, hash, &hashlen,
3152                                                         dig_signed,
3153                                                         dig_signed_len,
3154                                                         md_alg);
3155            if (ret != 0) {
3156                return ret;
3157            }
3158        } else {
3159            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3160            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3161        }
3162
3163        MBEDTLS_SSL_DEBUG_BUF(3, "parameters hash", hash, hashlen);
3164
3165        /*
3166         * 2.3: Compute and add the signature
3167         */
3168        /*
3169         * We need to specify signature and hash algorithm explicitly through
3170         * a prefix to the signature.
3171         *
3172         * struct {
3173         *    HashAlgorithm hash;
3174         *    SignatureAlgorithm signature;
3175         * } SignatureAndHashAlgorithm;
3176         *
3177         * struct {
3178         *    SignatureAndHashAlgorithm algorithm;
3179         *    opaque signature<0..2^16-1>;
3180         * } DigitallySigned;
3181         *
3182         */
3183
3184        ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_hash_from_md_alg(md_alg);
3185        ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_sig_from_pk_alg(sig_alg);
3186
3187#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3188        if (ssl->conf->f_async_sign_start != NULL) {
3189            ret = ssl->conf->f_async_sign_start(ssl,
3190                                                mbedtls_ssl_own_cert(ssl),
3191                                                md_alg, hash, hashlen);
3192            switch (ret) {
3193                case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3194                    /* act as if f_async_sign was null */
3195                    break;
3196                case 0:
3197                    ssl->handshake->async_in_progress = 1;
3198                    return ssl_resume_server_key_exchange(ssl, signature_len);
3199                case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3200                    ssl->handshake->async_in_progress = 1;
3201                    return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
3202                default:
3203                    MBEDTLS_SSL_DEBUG_RET(1, "f_async_sign_start", ret);
3204                    return ret;
3205            }
3206        }
3207#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3208
3209        if (mbedtls_ssl_own_key(ssl) == NULL) {
3210            MBEDTLS_SSL_DEBUG_MSG(1, ("got no private key"));
3211            return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3212        }
3213
3214        /* Append the signature to ssl->out_msg, leaving 2 bytes for the
3215         * signature length which will be added in ssl_write_server_key_exchange
3216         * after the call to ssl_prepare_server_key_exchange.
3217         * ssl_write_server_key_exchange also takes care of incrementing
3218         * ssl->out_msglen. */
3219        if ((ret = mbedtls_pk_sign(mbedtls_ssl_own_key(ssl),
3220                                   md_alg, hash, hashlen,
3221                                   ssl->out_msg + ssl->out_msglen + 2,
3222                                   out_buf_len - ssl->out_msglen - 2,
3223                                   signature_len,
3224                                   ssl->conf->f_rng,
3225                                   ssl->conf->p_rng)) != 0) {
3226            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_sign", ret);
3227            return ret;
3228        }
3229    }
3230#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3231
3232    return 0;
3233}
3234
3235/* Prepare the ServerKeyExchange message and send it. For ciphersuites
3236 * that do not include a ServerKeyExchange message, do nothing. Either
3237 * way, if successful, move on to the next step in the SSL state
3238 * machine. */
3239MBEDTLS_CHECK_RETURN_CRITICAL
3240static int ssl_write_server_key_exchange(mbedtls_ssl_context *ssl)
3241{
3242    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3243    size_t signature_len = 0;
3244#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3245    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3246        ssl->handshake->ciphersuite_info;
3247#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3248
3249    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server key exchange"));
3250
3251#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3252    /* Extract static ECDH parameters and abort if ServerKeyExchange
3253     * is not needed. */
3254    if (mbedtls_ssl_ciphersuite_no_pfs(ciphersuite_info)) {
3255        /* For suites involving ECDH, extract DH parameters
3256         * from certificate at this point. */
3257#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED)
3258        if (mbedtls_ssl_ciphersuite_uses_ecdh(ciphersuite_info)) {
3259            ret = ssl_get_ecdh_params_from_cert(ssl);
3260            if (ret != 0) {
3261                MBEDTLS_SSL_DEBUG_RET(1, "ssl_get_ecdh_params_from_cert", ret);
3262                return ret;
3263            }
3264        }
3265#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */
3266
3267        /* Key exchanges not involving ephemeral keys don't use
3268         * ServerKeyExchange, so end here. */
3269        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write server key exchange"));
3270        ssl->state++;
3271        return 0;
3272    }
3273#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3274
3275#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
3276    defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3277    /* If we have already prepared the message and there is an ongoing
3278     * signature operation, resume signing. */
3279    if (ssl->handshake->async_in_progress != 0) {
3280        MBEDTLS_SSL_DEBUG_MSG(2, ("resuming signature operation"));
3281        ret = ssl_resume_server_key_exchange(ssl, &signature_len);
3282    } else
3283#endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
3284          defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
3285    {
3286        /* ServerKeyExchange is needed. Prepare the message. */
3287        ret = ssl_prepare_server_key_exchange(ssl, &signature_len);
3288    }
3289
3290    if (ret != 0) {
3291        /* If we're starting to write a new message, set ssl->out_msglen
3292         * to 0. But if we're resuming after an asynchronous message,
3293         * out_msglen is the amount of data written so far and mst be
3294         * preserved. */
3295        if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3296            MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange (pending)"));
3297        } else {
3298            ssl->out_msglen = 0;
3299        }
3300        return ret;
3301    }
3302
3303    /* If there is a signature, write its length.
3304     * ssl_prepare_server_key_exchange already wrote the signature
3305     * itself at its proper place in the output buffer. */
3306#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3307    if (signature_len != 0) {
3308        ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_1(signature_len);
3309        ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_0(signature_len);
3310
3311        MBEDTLS_SSL_DEBUG_BUF(3, "my signature",
3312                              ssl->out_msg + ssl->out_msglen,
3313                              signature_len);
3314
3315        /* Skip over the already-written signature */
3316        ssl->out_msglen += signature_len;
3317    }
3318#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3319
3320    /* Add header and send. */
3321    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3322    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
3323
3324    ssl->state++;
3325
3326    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3327        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3328        return ret;
3329    }
3330
3331    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange"));
3332    return 0;
3333}
3334
3335MBEDTLS_CHECK_RETURN_CRITICAL
3336static int ssl_write_server_hello_done(mbedtls_ssl_context *ssl)
3337{
3338    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3339
3340    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello done"));
3341
3342    ssl->out_msglen  = 4;
3343    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3344    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
3345
3346    ssl->state++;
3347
3348#if defined(MBEDTLS_SSL_PROTO_DTLS)
3349    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3350        mbedtls_ssl_send_flight_completed(ssl);
3351    }
3352#endif
3353
3354    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3355        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3356        return ret;
3357    }
3358
3359#if defined(MBEDTLS_SSL_PROTO_DTLS)
3360    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3361        (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
3362        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
3363        return ret;
3364    }
3365#endif /* MBEDTLS_SSL_PROTO_DTLS */
3366
3367    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello done"));
3368
3369    return 0;
3370}
3371
3372#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
3373    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3374MBEDTLS_CHECK_RETURN_CRITICAL
3375static int ssl_parse_client_dh_public(mbedtls_ssl_context *ssl, unsigned char **p,
3376                                      const unsigned char *end)
3377{
3378    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3379    size_t n;
3380
3381    /*
3382     * Receive G^Y mod P, premaster = (G^Y)^X mod P
3383     */
3384    if (*p + 2 > end) {
3385        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3386        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3387    }
3388
3389    n = MBEDTLS_GET_UINT16_BE(*p, 0);
3390    *p += 2;
3391
3392    if (*p + n > end) {
3393        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3394        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3395    }
3396
3397    if ((ret = mbedtls_dhm_read_public(&ssl->handshake->dhm_ctx, *p, n)) != 0) {
3398        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_read_public", ret);
3399        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3400    }
3401
3402    *p += n;
3403
3404    MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GY", &ssl->handshake->dhm_ctx.GY);
3405
3406    return ret;
3407}
3408#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
3409          MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3410
3411#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
3412    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3413
3414#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3415MBEDTLS_CHECK_RETURN_CRITICAL
3416static int ssl_resume_decrypt_pms(mbedtls_ssl_context *ssl,
3417                                  unsigned char *peer_pms,
3418                                  size_t *peer_pmslen,
3419                                  size_t peer_pmssize)
3420{
3421    int ret = ssl->conf->f_async_resume(ssl,
3422                                        peer_pms, peer_pmslen, peer_pmssize);
3423    if (ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3424        ssl->handshake->async_in_progress = 0;
3425        mbedtls_ssl_set_async_operation_data(ssl, NULL);
3426    }
3427    MBEDTLS_SSL_DEBUG_RET(2, "ssl_decrypt_encrypted_pms", ret);
3428    return ret;
3429}
3430#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3431
3432MBEDTLS_CHECK_RETURN_CRITICAL
3433static int ssl_decrypt_encrypted_pms(mbedtls_ssl_context *ssl,
3434                                     const unsigned char *p,
3435                                     const unsigned char *end,
3436                                     unsigned char *peer_pms,
3437                                     size_t *peer_pmslen,
3438                                     size_t peer_pmssize)
3439{
3440    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3441
3442    mbedtls_x509_crt *own_cert = mbedtls_ssl_own_cert(ssl);
3443    if (own_cert == NULL) {
3444        MBEDTLS_SSL_DEBUG_MSG(1, ("got no local certificate"));
3445        return MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
3446    }
3447    mbedtls_pk_context *public_key = &own_cert->pk;
3448    mbedtls_pk_context *private_key = mbedtls_ssl_own_key(ssl);
3449    size_t len = mbedtls_pk_get_len(public_key);
3450
3451#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3452    /* If we have already started decoding the message and there is an ongoing
3453     * decryption operation, resume signing. */
3454    if (ssl->handshake->async_in_progress != 0) {
3455        MBEDTLS_SSL_DEBUG_MSG(2, ("resuming decryption operation"));
3456        return ssl_resume_decrypt_pms(ssl,
3457                                      peer_pms, peer_pmslen, peer_pmssize);
3458    }
3459#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3460
3461    /*
3462     * Prepare to decrypt the premaster using own private RSA key
3463     */
3464    if (p + 2 > end) {
3465        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3466        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3467    }
3468    if (*p++ != MBEDTLS_BYTE_1(len) ||
3469        *p++ != MBEDTLS_BYTE_0(len)) {
3470        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3471        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3472    }
3473
3474    if (p + len != end) {
3475        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3476        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3477    }
3478
3479    /*
3480     * Decrypt the premaster secret
3481     */
3482#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3483    if (ssl->conf->f_async_decrypt_start != NULL) {
3484        ret = ssl->conf->f_async_decrypt_start(ssl,
3485                                               mbedtls_ssl_own_cert(ssl),
3486                                               p, len);
3487        switch (ret) {
3488            case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3489                /* act as if f_async_decrypt_start was null */
3490                break;
3491            case 0:
3492                ssl->handshake->async_in_progress = 1;
3493                return ssl_resume_decrypt_pms(ssl,
3494                                              peer_pms,
3495                                              peer_pmslen,
3496                                              peer_pmssize);
3497            case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3498                ssl->handshake->async_in_progress = 1;
3499                return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
3500            default:
3501                MBEDTLS_SSL_DEBUG_RET(1, "f_async_decrypt_start", ret);
3502                return ret;
3503        }
3504    }
3505#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3506
3507    if (!mbedtls_pk_can_do(private_key, MBEDTLS_PK_RSA)) {
3508        MBEDTLS_SSL_DEBUG_MSG(1, ("got no RSA private key"));
3509        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3510    }
3511
3512    ret = mbedtls_pk_decrypt(private_key, p, len,
3513                             peer_pms, peer_pmslen, peer_pmssize,
3514                             ssl->conf->f_rng, ssl->conf->p_rng);
3515    return ret;
3516}
3517
3518MBEDTLS_CHECK_RETURN_CRITICAL
3519static int ssl_parse_encrypted_pms(mbedtls_ssl_context *ssl,
3520                                   const unsigned char *p,
3521                                   const unsigned char *end,
3522                                   size_t pms_offset)
3523{
3524    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3525    unsigned char *pms = ssl->handshake->premaster + pms_offset;
3526    unsigned char ver[2];
3527    unsigned char fake_pms[48], peer_pms[48];
3528    size_t peer_pmslen;
3529    mbedtls_ct_condition_t diff;
3530
3531    /* In case of a failure in decryption, the decryption may write less than
3532     * 2 bytes of output, but we always read the first two bytes. It doesn't
3533     * matter in the end because diff will be nonzero in that case due to
3534     * ret being nonzero, and we only care whether diff is 0.
3535     * But do initialize peer_pms and peer_pmslen for robustness anyway. This
3536     * also makes memory analyzers happy (don't access uninitialized memory,
3537     * even if it's an unsigned char). */
3538    peer_pms[0] = peer_pms[1] = ~0;
3539    peer_pmslen = 0;
3540
3541    ret = ssl_decrypt_encrypted_pms(ssl, p, end,
3542                                    peer_pms,
3543                                    &peer_pmslen,
3544                                    sizeof(peer_pms));
3545
3546#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3547    if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3548        return ret;
3549    }
3550#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3551
3552    mbedtls_ssl_write_version(ver, ssl->conf->transport,
3553                              ssl->session_negotiate->tls_version);
3554
3555    /* Avoid data-dependent branches while checking for invalid
3556     * padding, to protect against timing-based Bleichenbacher-type
3557     * attacks. */
3558    diff = mbedtls_ct_bool(ret);
3559    diff = mbedtls_ct_bool_or(diff, mbedtls_ct_uint_ne(peer_pmslen, 48));
3560    diff = mbedtls_ct_bool_or(diff, mbedtls_ct_uint_ne(peer_pms[0], ver[0]));
3561    diff = mbedtls_ct_bool_or(diff, mbedtls_ct_uint_ne(peer_pms[1], ver[1]));
3562
3563    /*
3564     * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding
3565     * must not cause the connection to end immediately; instead, send a
3566     * bad_record_mac later in the handshake.
3567     * To protect against timing-based variants of the attack, we must
3568     * not have any branch that depends on whether the decryption was
3569     * successful. In particular, always generate the fake premaster secret,
3570     * regardless of whether it will ultimately influence the output or not.
3571     */
3572    ret = ssl->conf->f_rng(ssl->conf->p_rng, fake_pms, sizeof(fake_pms));
3573    if (ret != 0) {
3574        /* It's ok to abort on an RNG failure, since this does not reveal
3575         * anything about the RSA decryption. */
3576        return ret;
3577    }
3578
3579#if defined(MBEDTLS_SSL_DEBUG_ALL)
3580    if (diff != MBEDTLS_CT_FALSE) {
3581        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3582    }
3583#endif
3584
3585    if (sizeof(ssl->handshake->premaster) < pms_offset ||
3586        sizeof(ssl->handshake->premaster) - pms_offset < 48) {
3587        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3588        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3589    }
3590    ssl->handshake->pmslen = 48;
3591
3592    /* Set pms to either the true or the fake PMS, without
3593     * data-dependent branches. */
3594    mbedtls_ct_memcpy_if(diff, pms, fake_pms, peer_pms, ssl->handshake->pmslen);
3595
3596    return 0;
3597}
3598#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
3599          MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
3600
3601#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
3602MBEDTLS_CHECK_RETURN_CRITICAL
3603static int ssl_parse_client_psk_identity(mbedtls_ssl_context *ssl, unsigned char **p,
3604                                         const unsigned char *end)
3605{
3606    int ret = 0;
3607    uint16_t n;
3608
3609    if (ssl_conf_has_psk_or_cb(ssl->conf) == 0) {
3610        MBEDTLS_SSL_DEBUG_MSG(1, ("got no pre-shared key"));
3611        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3612    }
3613
3614    /*
3615     * Receive client pre-shared key identity name
3616     */
3617    if (end - *p < 2) {
3618        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3619        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3620    }
3621
3622    n = MBEDTLS_GET_UINT16_BE(*p, 0);
3623    *p += 2;
3624
3625    if (n == 0 || n > end - *p) {
3626        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3627        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3628    }
3629
3630    if (ssl->conf->f_psk != NULL) {
3631        if (ssl->conf->f_psk(ssl->conf->p_psk, ssl, *p, n) != 0) {
3632            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3633        }
3634    } else {
3635        /* Identity is not a big secret since clients send it in the clear,
3636         * but treat it carefully anyway, just in case */
3637        if (n != ssl->conf->psk_identity_len ||
3638            mbedtls_ct_memcmp(ssl->conf->psk_identity, *p, n) != 0) {
3639            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3640        }
3641    }
3642
3643    if (ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
3644        MBEDTLS_SSL_DEBUG_BUF(3, "Unknown PSK identity", *p, n);
3645        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3646                                       MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY);
3647        return MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3648    }
3649
3650    *p += n;
3651
3652    return 0;
3653}
3654#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
3655
3656MBEDTLS_CHECK_RETURN_CRITICAL
3657static int ssl_parse_client_key_exchange(mbedtls_ssl_context *ssl)
3658{
3659    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3660    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3661    unsigned char *p, *end;
3662
3663    ciphersuite_info = ssl->handshake->ciphersuite_info;
3664
3665    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client key exchange"));
3666
3667#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
3668    (defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
3669    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED))
3670    if ((ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3671         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) &&
3672        (ssl->handshake->async_in_progress != 0)) {
3673        /* We've already read a record and there is an asynchronous
3674         * operation in progress to decrypt it. So skip reading the
3675         * record. */
3676        MBEDTLS_SSL_DEBUG_MSG(3, ("will resume decryption of previously-read record"));
3677    } else
3678#endif
3679    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3680        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3681        return ret;
3682    }
3683
3684    p = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
3685    end = ssl->in_msg + ssl->in_hslen;
3686
3687    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
3688        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3689        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3690    }
3691
3692    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE) {
3693        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3694        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3695    }
3696
3697#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
3698    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA) {
3699        if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
3700            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
3701            return ret;
3702        }
3703
3704        if (p != end) {
3705            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3706            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3707        }
3708
3709        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
3710                                           ssl->handshake->premaster,
3711                                           MBEDTLS_PREMASTER_SIZE,
3712                                           &ssl->handshake->pmslen,
3713                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3714            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
3715            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3716        }
3717
3718        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
3719    } else
3720#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
3721#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
3722    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
3723    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
3724    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
3725    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3726        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
3727        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
3728        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA) {
3729#if defined(MBEDTLS_USE_PSA_CRYPTO)
3730        size_t data_len = (size_t) (*p++);
3731        size_t buf_len = (size_t) (end - p);
3732        psa_status_t status = PSA_ERROR_GENERIC_ERROR;
3733        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3734
3735        MBEDTLS_SSL_DEBUG_MSG(3, ("Read the peer's public key."));
3736
3737        /*
3738         * We must have at least two bytes (1 for length, at least 1 for data)
3739         */
3740        if (buf_len < 2) {
3741            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid buffer length: %" MBEDTLS_PRINTF_SIZET,
3742                                      buf_len));
3743            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3744        }
3745
3746        if (data_len < 1 || data_len > buf_len) {
3747            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid data length: %" MBEDTLS_PRINTF_SIZET
3748                                      " > %" MBEDTLS_PRINTF_SIZET,
3749                                      data_len, buf_len));
3750            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3751        }
3752
3753        /* Store peer's ECDH public key. */
3754        if (data_len > sizeof(handshake->xxdh_psa_peerkey)) {
3755            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid public key length: %" MBEDTLS_PRINTF_SIZET
3756                                      " > %" MBEDTLS_PRINTF_SIZET,
3757                                      data_len,
3758                                      sizeof(handshake->xxdh_psa_peerkey)));
3759            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3760        }
3761        memcpy(handshake->xxdh_psa_peerkey, p, data_len);
3762        handshake->xxdh_psa_peerkey_len = data_len;
3763
3764        /* Compute ECDH shared secret. */
3765        status = psa_raw_key_agreement(
3766            PSA_ALG_ECDH, handshake->xxdh_psa_privkey,
3767            handshake->xxdh_psa_peerkey, handshake->xxdh_psa_peerkey_len,
3768            handshake->premaster, sizeof(handshake->premaster),
3769            &handshake->pmslen);
3770        if (status != PSA_SUCCESS) {
3771            ret = PSA_TO_MBEDTLS_ERR(status);
3772            MBEDTLS_SSL_DEBUG_RET(1, "psa_raw_key_agreement", ret);
3773            if (handshake->xxdh_psa_privkey_is_external == 0) {
3774                (void) psa_destroy_key(handshake->xxdh_psa_privkey);
3775            }
3776            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3777            return ret;
3778        }
3779
3780        if (handshake->xxdh_psa_privkey_is_external == 0) {
3781            status = psa_destroy_key(handshake->xxdh_psa_privkey);
3782
3783            if (status != PSA_SUCCESS) {
3784                ret = PSA_TO_MBEDTLS_ERR(status);
3785                MBEDTLS_SSL_DEBUG_RET(1, "psa_destroy_key", ret);
3786                return ret;
3787            }
3788        }
3789        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3790#else
3791        if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
3792                                            p, (size_t) (end - p))) != 0) {
3793            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
3794            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3795        }
3796
3797        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3798                               MBEDTLS_DEBUG_ECDH_QP);
3799
3800        if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx,
3801                                            &ssl->handshake->pmslen,
3802                                            ssl->handshake->premaster,
3803                                            MBEDTLS_MPI_MAX_SIZE,
3804                                            ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3805            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
3806            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3807        }
3808
3809        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3810                               MBEDTLS_DEBUG_ECDH_Z);
3811#endif /* MBEDTLS_USE_PSA_CRYPTO */
3812    } else
3813#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3814          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
3815          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
3816          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3817#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
3818    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK) {
3819        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3820            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3821            return ret;
3822        }
3823
3824        if (p != end) {
3825            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3826            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3827        }
3828
3829#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3830        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3831                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3832                                                    key_exchange)) != 0) {
3833            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3834            return ret;
3835        }
3836#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3837    } else
3838#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
3839#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3840    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
3841#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3842        if (ssl->handshake->async_in_progress != 0) {
3843            /* There is an asynchronous operation in progress to
3844             * decrypt the encrypted premaster secret, so skip
3845             * directly to resuming this operation. */
3846            MBEDTLS_SSL_DEBUG_MSG(3, ("PSK identity already parsed"));
3847            /* Update p to skip the PSK identity. ssl_parse_encrypted_pms
3848             * won't actually use it, but maintain p anyway for robustness. */
3849            p += ssl->conf->psk_identity_len + 2;
3850        } else
3851#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3852        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3853            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3854            return ret;
3855        }
3856
3857        if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 2)) != 0) {
3858            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_encrypted_pms"), ret);
3859            return ret;
3860        }
3861
3862#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3863        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3864                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3865                                                    key_exchange)) != 0) {
3866            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3867            return ret;
3868        }
3869#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3870    } else
3871#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
3872#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3873    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
3874        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3875            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3876            return ret;
3877        }
3878        if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
3879            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
3880            return ret;
3881        }
3882
3883        if (p != end) {
3884            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3885            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3886        }
3887
3888#if defined(MBEDTLS_USE_PSA_CRYPTO)
3889        unsigned char *pms = ssl->handshake->premaster;
3890        unsigned char *pms_end = pms + sizeof(ssl->handshake->premaster);
3891        size_t pms_len;
3892
3893        /* Write length only when we know the actual value */
3894        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
3895                                           pms + 2, pms_end - (pms + 2), &pms_len,
3896                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3897            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
3898            return ret;
3899        }
3900        MBEDTLS_PUT_UINT16_BE(pms_len, pms, 0);
3901        pms += 2 + pms_len;
3902
3903        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
3904#else
3905        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3906                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3907                                                    key_exchange)) != 0) {
3908            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3909            return ret;
3910        }
3911#endif /* MBEDTLS_USE_PSA_CRYPTO */
3912    } else
3913#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3914#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3915    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
3916#if defined(MBEDTLS_USE_PSA_CRYPTO)
3917        psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3918        psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
3919        uint8_t ecpoint_len;
3920
3921        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3922
3923        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3924            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3925            psa_destroy_key(handshake->xxdh_psa_privkey);
3926            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3927            return ret;
3928        }
3929
3930        /* Keep a copy of the peer's public key */
3931        if (p >= end) {
3932            psa_destroy_key(handshake->xxdh_psa_privkey);
3933            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3934            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3935        }
3936
3937        ecpoint_len = *(p++);
3938        if ((size_t) (end - p) < ecpoint_len) {
3939            psa_destroy_key(handshake->xxdh_psa_privkey);
3940            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3941            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3942        }
3943
3944        /* When FFDH is enabled, the array handshake->xxdh_psa_peer_key size takes into account
3945           the sizes of the FFDH keys which are at least 2048 bits.
3946           The size of the array is thus greater than 256 bytes which is greater than any
3947           possible value of ecpoint_len (type uint8_t) and the check below can be skipped.*/
3948#if !defined(PSA_WANT_ALG_FFDH)
3949        if (ecpoint_len > sizeof(handshake->xxdh_psa_peerkey)) {
3950            psa_destroy_key(handshake->xxdh_psa_privkey);
3951            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3952            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3953        }
3954#else
3955        MBEDTLS_STATIC_ASSERT(sizeof(handshake->xxdh_psa_peerkey) >= UINT8_MAX,
3956                              "peer key buffer too small");
3957#endif
3958
3959        memcpy(handshake->xxdh_psa_peerkey, p, ecpoint_len);
3960        handshake->xxdh_psa_peerkey_len = ecpoint_len;
3961        p += ecpoint_len;
3962
3963        /* As RFC 5489 section 2, the premaster secret is formed as follows:
3964         * - a uint16 containing the length (in octets) of the ECDH computation
3965         * - the octet string produced by the ECDH computation
3966         * - a uint16 containing the length (in octets) of the PSK
3967         * - the PSK itself
3968         */
3969        unsigned char *psm = ssl->handshake->premaster;
3970        const unsigned char * const psm_end =
3971            psm + sizeof(ssl->handshake->premaster);
3972        /* uint16 to store length (in octets) of the ECDH computation */
3973        const size_t zlen_size = 2;
3974        size_t zlen = 0;
3975
3976        /* Compute ECDH shared secret. */
3977        status = psa_raw_key_agreement(PSA_ALG_ECDH,
3978                                       handshake->xxdh_psa_privkey,
3979                                       handshake->xxdh_psa_peerkey,
3980                                       handshake->xxdh_psa_peerkey_len,
3981                                       psm + zlen_size,
3982                                       psm_end - (psm + zlen_size),
3983                                       &zlen);
3984
3985        destruction_status = psa_destroy_key(handshake->xxdh_psa_privkey);
3986        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3987
3988        if (status != PSA_SUCCESS) {
3989            return PSA_TO_MBEDTLS_ERR(status);
3990        } else if (destruction_status != PSA_SUCCESS) {
3991            return PSA_TO_MBEDTLS_ERR(destruction_status);
3992        }
3993
3994        /* Write the ECDH computation length before the ECDH computation */
3995        MBEDTLS_PUT_UINT16_BE(zlen, psm, 0);
3996        psm += zlen_size + zlen;
3997
3998#else /* MBEDTLS_USE_PSA_CRYPTO */
3999        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
4000            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
4001            return ret;
4002        }
4003
4004        if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
4005                                            p, (size_t) (end - p))) != 0) {
4006            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
4007            return MBEDTLS_ERR_SSL_DECODE_ERROR;
4008        }
4009
4010        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
4011                               MBEDTLS_DEBUG_ECDH_QP);
4012
4013        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
4014                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
4015                                                    key_exchange)) != 0) {
4016            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
4017            return ret;
4018        }
4019#endif /* MBEDTLS_USE_PSA_CRYPTO */
4020    } else
4021#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
4022#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
4023    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) {
4024        if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 0)) != 0) {
4025            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_parse_encrypted_pms_secret"), ret);
4026            return ret;
4027        }
4028    } else
4029#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
4030#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4031    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
4032#if defined(MBEDTLS_USE_PSA_CRYPTO)
4033        if ((ret = mbedtls_psa_ecjpake_read_round(
4034                 &ssl->handshake->psa_pake_ctx, p, (size_t) (end - p),
4035                 MBEDTLS_ECJPAKE_ROUND_TWO)) != 0) {
4036            psa_destroy_key(ssl->handshake->psa_pake_password);
4037            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
4038
4039            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_input round two", ret);
4040            return ret;
4041        }
4042#else
4043        ret = mbedtls_ecjpake_read_round_two(&ssl->handshake->ecjpake_ctx,
4044                                             p, (size_t) (end - p));
4045        if (ret != 0) {
4046            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_two", ret);
4047            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4048        }
4049
4050        ret = mbedtls_ecjpake_derive_secret(&ssl->handshake->ecjpake_ctx,
4051                                            ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
4052                                            ssl->conf->f_rng, ssl->conf->p_rng);
4053        if (ret != 0) {
4054            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_derive_secret", ret);
4055            return ret;
4056        }
4057#endif /* MBEDTLS_USE_PSA_CRYPTO */
4058    } else
4059#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4060    {
4061        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4062        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4063    }
4064
4065    if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
4066        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
4067        return ret;
4068    }
4069
4070    ssl->state++;
4071
4072    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client key exchange"));
4073
4074    return 0;
4075}
4076
4077#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
4078MBEDTLS_CHECK_RETURN_CRITICAL
4079static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl)
4080{
4081    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4082        ssl->handshake->ciphersuite_info;
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    MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4093    return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4094}
4095#else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4096MBEDTLS_CHECK_RETURN_CRITICAL
4097static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl)
4098{
4099    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4100    size_t i, sig_len;
4101    unsigned char hash[48];
4102    unsigned char *hash_start = hash;
4103    size_t hashlen;
4104    mbedtls_pk_type_t pk_alg;
4105    mbedtls_md_type_t md_alg;
4106    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4107        ssl->handshake->ciphersuite_info;
4108    mbedtls_pk_context *peer_pk;
4109
4110    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate verify"));
4111
4112    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
4113        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4114        ssl->state++;
4115        return 0;
4116    }
4117
4118#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4119    if (ssl->session_negotiate->peer_cert == NULL) {
4120        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4121        ssl->state++;
4122        return 0;
4123    }
4124#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4125    if (ssl->session_negotiate->peer_cert_digest == NULL) {
4126        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4127        ssl->state++;
4128        return 0;
4129    }
4130#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4131
4132    /* Read the message without adding it to the checksum */
4133    ret = mbedtls_ssl_read_record(ssl, 0 /* no checksum update */);
4134    if (0 != ret) {
4135        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_read_record"), ret);
4136        return ret;
4137    }
4138
4139    ssl->state++;
4140
4141    /* Process the message contents */
4142    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
4143        ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY) {
4144        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4145        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
4146    }
4147
4148    i = mbedtls_ssl_hs_hdr_len(ssl);
4149
4150#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4151    peer_pk = &ssl->handshake->peer_pubkey;
4152#else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4153    if (ssl->session_negotiate->peer_cert == NULL) {
4154        /* Should never happen */
4155        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4156    }
4157    peer_pk = &ssl->session_negotiate->peer_cert->pk;
4158#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4159
4160    /*
4161     *  struct {
4162     *     SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only
4163     *     opaque signature<0..2^16-1>;
4164     *  } DigitallySigned;
4165     */
4166    if (i + 2 > ssl->in_hslen) {
4167        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4168        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4169    }
4170
4171    /*
4172     * Hash
4173     */
4174    md_alg = mbedtls_ssl_md_alg_from_hash(ssl->in_msg[i]);
4175
4176    if (md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md(ssl, ssl->in_msg[i])) {
4177        MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4178                                  " for verify message"));
4179        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4180    }
4181
4182#if !defined(MBEDTLS_MD_SHA1)
4183    if (MBEDTLS_MD_SHA1 == md_alg) {
4184        hash_start += 16;
4185    }
4186#endif
4187
4188    /* Info from md_alg will be used instead */
4189    hashlen = 0;
4190
4191    i++;
4192
4193    /*
4194     * Signature
4195     */
4196    if ((pk_alg = mbedtls_ssl_pk_alg_from_sig(ssl->in_msg[i]))
4197        == MBEDTLS_PK_NONE) {
4198        MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4199                                  " for verify message"));
4200        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4201    }
4202
4203    /*
4204     * Check the certificate's key type matches the signature alg
4205     */
4206    if (!mbedtls_pk_can_do(peer_pk, pk_alg)) {
4207        MBEDTLS_SSL_DEBUG_MSG(1, ("sig_alg doesn't match cert key"));
4208        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4209    }
4210
4211    i++;
4212
4213    if (i + 2 > ssl->in_hslen) {
4214        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4215        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4216    }
4217
4218    sig_len = MBEDTLS_GET_UINT16_BE(ssl->in_msg, i);
4219    i += 2;
4220
4221    if (i + sig_len != ssl->in_hslen) {
4222        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4223        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4224    }
4225
4226    /* Calculate hash and verify signature */
4227    {
4228        size_t dummy_hlen;
4229        ret = ssl->handshake->calc_verify(ssl, hash, &dummy_hlen);
4230        if (0 != ret) {
4231            MBEDTLS_SSL_DEBUG_RET(1, ("calc_verify"), ret);
4232            return ret;
4233        }
4234    }
4235
4236    if ((ret = mbedtls_pk_verify(peer_pk,
4237                                 md_alg, hash_start, hashlen,
4238                                 ssl->in_msg + i, sig_len)) != 0) {
4239        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify", ret);
4240        return ret;
4241    }
4242
4243    ret = mbedtls_ssl_update_handshake_status(ssl);
4244    if (0 != ret) {
4245        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_update_handshake_status"), ret);
4246        return ret;
4247    }
4248
4249    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate verify"));
4250
4251    return ret;
4252}
4253#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4254
4255#if defined(MBEDTLS_SSL_SESSION_TICKETS)
4256MBEDTLS_CHECK_RETURN_CRITICAL
4257static int ssl_write_new_session_ticket(mbedtls_ssl_context *ssl)
4258{
4259    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4260    size_t tlen;
4261    uint32_t lifetime;
4262
4263    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write new session ticket"));
4264
4265    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4266    ssl->out_msg[0]  = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;
4267
4268    /*
4269     * struct {
4270     *     uint32 ticket_lifetime_hint;
4271     *     opaque ticket<0..2^16-1>;
4272     * } NewSessionTicket;
4273     *
4274     * 4  .  7   ticket_lifetime_hint (0 = unspecified)
4275     * 8  .  9   ticket_len (n)
4276     * 10 .  9+n ticket content
4277     */
4278
4279#if defined(MBEDTLS_HAVE_TIME)
4280    ssl->session_negotiate->ticket_creation_time = mbedtls_ms_time();
4281#endif
4282    if ((ret = ssl->conf->f_ticket_write(ssl->conf->p_ticket,
4283                                         ssl->session_negotiate,
4284                                         ssl->out_msg + 10,
4285                                         ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
4286                                         &tlen, &lifetime)) != 0) {
4287        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_ticket_write", ret);
4288        tlen = 0;
4289    }
4290
4291    MBEDTLS_PUT_UINT32_BE(lifetime, ssl->out_msg, 4);
4292    MBEDTLS_PUT_UINT16_BE(tlen, ssl->out_msg, 8);
4293    ssl->out_msglen = 10 + tlen;
4294
4295    /*
4296     * Morally equivalent to updating ssl->state, but NewSessionTicket and
4297     * ChangeCipherSpec share the same state.
4298     */
4299    ssl->handshake->new_session_ticket = 0;
4300
4301    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
4302        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
4303        return ret;
4304    }
4305
4306    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write new session ticket"));
4307
4308    return 0;
4309}
4310#endif /* MBEDTLS_SSL_SESSION_TICKETS */
4311
4312/*
4313 * SSL handshake -- server side -- single step
4314 */
4315int mbedtls_ssl_handshake_server_step(mbedtls_ssl_context *ssl)
4316{
4317    int ret = 0;
4318
4319    MBEDTLS_SSL_DEBUG_MSG(2, ("server state: %d", ssl->state));
4320
4321    switch (ssl->state) {
4322        case MBEDTLS_SSL_HELLO_REQUEST:
4323            ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
4324            break;
4325
4326        /*
4327         *  <==   ClientHello
4328         */
4329        case MBEDTLS_SSL_CLIENT_HELLO:
4330            ret = ssl_parse_client_hello(ssl);
4331            break;
4332
4333#if defined(MBEDTLS_SSL_PROTO_DTLS)
4334        case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
4335            return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED;
4336#endif
4337
4338        /*
4339         *  ==>   ServerHello
4340         *        Certificate
4341         *      ( ServerKeyExchange  )
4342         *      ( CertificateRequest )
4343         *        ServerHelloDone
4344         */
4345        case MBEDTLS_SSL_SERVER_HELLO:
4346            ret = ssl_write_server_hello(ssl);
4347            break;
4348
4349        case MBEDTLS_SSL_SERVER_CERTIFICATE:
4350            ret = mbedtls_ssl_write_certificate(ssl);
4351            break;
4352
4353        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
4354            ret = ssl_write_server_key_exchange(ssl);
4355            break;
4356
4357        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
4358            ret = ssl_write_certificate_request(ssl);
4359            break;
4360
4361        case MBEDTLS_SSL_SERVER_HELLO_DONE:
4362            ret = ssl_write_server_hello_done(ssl);
4363            break;
4364
4365        /*
4366         *  <== ( Certificate/Alert  )
4367         *        ClientKeyExchange
4368         *      ( CertificateVerify  )
4369         *        ChangeCipherSpec
4370         *        Finished
4371         */
4372        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
4373            ret = mbedtls_ssl_parse_certificate(ssl);
4374            break;
4375
4376        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
4377            ret = ssl_parse_client_key_exchange(ssl);
4378            break;
4379
4380        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
4381            ret = ssl_parse_certificate_verify(ssl);
4382            break;
4383
4384        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
4385            ret = mbedtls_ssl_parse_change_cipher_spec(ssl);
4386            break;
4387
4388        case MBEDTLS_SSL_CLIENT_FINISHED:
4389            ret = mbedtls_ssl_parse_finished(ssl);
4390            break;
4391
4392        /*
4393         *  ==> ( NewSessionTicket )
4394         *        ChangeCipherSpec
4395         *        Finished
4396         */
4397        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
4398#if defined(MBEDTLS_SSL_SESSION_TICKETS)
4399            if (ssl->handshake->new_session_ticket != 0) {
4400                ret = ssl_write_new_session_ticket(ssl);
4401            } else
4402#endif
4403            ret = mbedtls_ssl_write_change_cipher_spec(ssl);
4404            break;
4405
4406        case MBEDTLS_SSL_SERVER_FINISHED:
4407            ret = mbedtls_ssl_write_finished(ssl);
4408            break;
4409
4410        case MBEDTLS_SSL_FLUSH_BUFFERS:
4411            MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
4412            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
4413            break;
4414
4415        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
4416            mbedtls_ssl_handshake_wrapup(ssl);
4417            break;
4418
4419        default:
4420            MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
4421            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4422    }
4423
4424    return ret;
4425}
4426
4427void mbedtls_ssl_conf_preference_order(mbedtls_ssl_config *conf, int order)
4428{
4429    conf->respect_cli_pref = order;
4430}
4431
4432#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_PROTO_TLS1_2 */
4433