Coverage Report

Created: 2024-11-12 06:19

/src/openthread/third_party/mbedtls/repo/library/ssl_tls12_server.c
Line
Count
Source (jump to first uncovered line)
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)
29
static int local_err_translation(psa_status_t status)
30
{
31
    return psa_status_to_mbedtls(status, psa_to_ssl_errors,
32
                                 ARRAY_LENGTH(psa_to_ssl_errors),
33
                                 psa_generic_status_to_mbedtls);
34
}
35
#define PSA_TO_MBEDTLS_ERR(status) local_err_translation(status)
36
#endif
37
#endif
38
39
#if defined(MBEDTLS_ECP_C)
40
#include "mbedtls/ecp.h"
41
#endif
42
43
#if defined(MBEDTLS_HAVE_TIME)
44
#include "mbedtls/platform_time.h"
45
#endif
46
47
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
48
int mbedtls_ssl_set_client_transport_id(mbedtls_ssl_context *ssl,
49
                                        const unsigned char *info,
50
                                        size_t ilen)
51
5.22k
{
52
5.22k
    if (ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER) {
53
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
54
0
    }
55
56
5.22k
    mbedtls_free(ssl->cli_id);
57
58
5.22k
    if ((ssl->cli_id = mbedtls_calloc(1, ilen)) == NULL) {
59
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
60
0
    }
61
62
5.22k
    memcpy(ssl->cli_id, info, ilen);
63
5.22k
    ssl->cli_id_len = ilen;
64
65
5.22k
    return 0;
66
5.22k
}
67
68
void mbedtls_ssl_conf_dtls_cookies(mbedtls_ssl_config *conf,
69
                                   mbedtls_ssl_cookie_write_t *f_cookie_write,
70
                                   mbedtls_ssl_cookie_check_t *f_cookie_check,
71
                                   void *p_cookie)
72
4.89k
{
73
4.89k
    conf->f_cookie_write = f_cookie_write;
74
4.89k
    conf->f_cookie_check = f_cookie_check;
75
4.89k
    conf->p_cookie       = p_cookie;
76
4.89k
}
77
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
78
79
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
80
MBEDTLS_CHECK_RETURN_CRITICAL
81
static int ssl_conf_has_psk_or_cb(mbedtls_ssl_config const *conf)
82
0
{
83
0
    if (conf->f_psk != NULL) {
84
0
        return 1;
85
0
    }
86
87
0
    if (conf->psk_identity_len == 0 || conf->psk_identity == NULL) {
88
0
        return 0;
89
0
    }
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
0
    if (conf->psk != NULL && conf->psk_len != 0) {
99
0
        return 1;
100
0
    }
101
102
0
    return 0;
103
0
}
104
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
105
106
MBEDTLS_CHECK_RETURN_CRITICAL
107
static int ssl_parse_renegotiation_info(mbedtls_ssl_context *ssl,
108
                                        const unsigned char *buf,
109
                                        size_t len)
110
0
{
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
0
    {
126
0
        if (len != 1 || buf[0] != 0x0) {
127
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("non-zero length renegotiation info"));
128
0
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
129
0
                                           MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
130
0
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
131
0
        }
132
133
0
        ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
134
0
    }
135
136
0
    return 0;
137
0
}
138
139
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
140
    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
141
    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
142
/*
143
 * Function for parsing a supported groups (TLS 1.3) or supported elliptic
144
 * curves (TLS 1.2) extension.
145
 *
146
 * The "extension_data" field of a supported groups extension contains a
147
 * "NamedGroupList" value (TLS 1.3 RFC8446):
148
 *      enum {
149
 *          secp256r1(0x0017), secp384r1(0x0018), secp521r1(0x0019),
150
 *          x25519(0x001D), x448(0x001E),
151
 *          ffdhe2048(0x0100), ffdhe3072(0x0101), ffdhe4096(0x0102),
152
 *          ffdhe6144(0x0103), ffdhe8192(0x0104),
153
 *          ffdhe_private_use(0x01FC..0x01FF),
154
 *          ecdhe_private_use(0xFE00..0xFEFF),
155
 *          (0xFFFF)
156
 *      } NamedGroup;
157
 *      struct {
158
 *          NamedGroup named_group_list<2..2^16-1>;
159
 *      } NamedGroupList;
160
 *
161
 * The "extension_data" field of a supported elliptic curves extension contains
162
 * a "NamedCurveList" value (TLS 1.2 RFC 8422):
163
 * enum {
164
 *      deprecated(1..22),
165
 *      secp256r1 (23), secp384r1 (24), secp521r1 (25),
166
 *      x25519(29), x448(30),
167
 *      reserved (0xFE00..0xFEFF),
168
 *      deprecated(0xFF01..0xFF02),
169
 *      (0xFFFF)
170
 *  } NamedCurve;
171
 * struct {
172
 *      NamedCurve named_curve_list<2..2^16-1>
173
 *  } NamedCurveList;
174
 *
175
 * The TLS 1.3 supported groups extension was defined to be a compatible
176
 * generalization of the TLS 1.2 supported elliptic curves extension. They both
177
 * share the same extension identifier.
178
 *
179
 */
180
MBEDTLS_CHECK_RETURN_CRITICAL
181
static int ssl_parse_supported_groups_ext(mbedtls_ssl_context *ssl,
182
                                          const unsigned char *buf,
183
                                          size_t len)
184
0
{
185
0
    size_t list_size, our_size;
186
0
    const unsigned char *p;
187
0
    uint16_t *curves_tls_id;
188
189
0
    if (len < 2) {
190
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
191
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
192
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
193
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
194
0
    }
195
0
    list_size = MBEDTLS_GET_UINT16_BE(buf, 0);
196
0
    if (list_size + 2 != len ||
197
0
        list_size % 2 != 0) {
198
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
199
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
200
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
201
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
202
0
    }
203
204
    /* Should never happen unless client duplicates the extension */
205
0
    if (ssl->handshake->curves_tls_id != NULL) {
206
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
207
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
208
0
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
209
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
210
0
    }
211
212
    /* Don't allow our peer to make us allocate too much memory,
213
     * and leave room for a final 0 */
214
0
    our_size = list_size / 2 + 1;
215
0
    if (our_size > MBEDTLS_ECP_DP_MAX) {
216
0
        our_size = MBEDTLS_ECP_DP_MAX;
217
0
    }
218
219
0
    if ((curves_tls_id = mbedtls_calloc(our_size,
220
0
                                        sizeof(*curves_tls_id))) == NULL) {
221
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
222
0
                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
223
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
224
0
    }
225
226
0
    ssl->handshake->curves_tls_id = curves_tls_id;
227
228
0
    p = buf + 2;
229
0
    while (list_size > 0 && our_size > 1) {
230
0
        uint16_t curr_tls_id = MBEDTLS_GET_UINT16_BE(p, 0);
231
232
0
        if (mbedtls_ssl_get_ecp_group_id_from_tls_id(curr_tls_id) !=
233
0
            MBEDTLS_ECP_DP_NONE) {
234
0
            *curves_tls_id++ = curr_tls_id;
235
0
            our_size--;
236
0
        }
237
238
0
        list_size -= 2;
239
0
        p += 2;
240
0
    }
241
242
0
    return 0;
243
0
}
244
245
MBEDTLS_CHECK_RETURN_CRITICAL
246
static int ssl_parse_supported_point_formats(mbedtls_ssl_context *ssl,
247
                                             const unsigned char *buf,
248
                                             size_t len)
249
0
{
250
0
    size_t list_size;
251
0
    const unsigned char *p;
252
253
0
    if (len == 0 || (size_t) (buf[0] + 1) != len) {
254
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
255
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
256
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
257
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
258
0
    }
259
0
    list_size = buf[0];
260
261
0
    p = buf + 1;
262
0
    while (list_size > 0) {
263
0
        if (p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
264
0
            p[0] == MBEDTLS_ECP_PF_COMPRESSED) {
265
0
#if !defined(MBEDTLS_USE_PSA_CRYPTO) && \
266
0
            defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED)
267
0
            ssl->handshake->ecdh_ctx.point_format = p[0];
268
0
#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED */
269
0
#if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
270
0
            defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
271
0
            mbedtls_ecjpake_set_point_format(&ssl->handshake->ecjpake_ctx,
272
0
                                             p[0]);
273
0
#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
274
0
            MBEDTLS_SSL_DEBUG_MSG(4, ("point format selected: %d", p[0]));
275
0
            return 0;
276
0
        }
277
278
0
        list_size--;
279
0
        p++;
280
0
    }
281
282
0
    return 0;
283
0
}
284
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED ||
285
          MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED ||
286
          MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
287
288
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
289
MBEDTLS_CHECK_RETURN_CRITICAL
290
static int ssl_parse_ecjpake_kkpp(mbedtls_ssl_context *ssl,
291
                                  const unsigned char *buf,
292
                                  size_t len)
293
0
{
294
0
    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
0
    if (mbedtls_ecjpake_check(&ssl->handshake->ecjpake_ctx) != 0)
300
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
301
0
    {
302
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("skip ecjpake kkpp extension"));
303
0
        return 0;
304
0
    }
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
0
    if ((ret = mbedtls_ecjpake_read_round_one(&ssl->handshake->ecjpake_ctx,
323
0
                                              buf, len)) != 0) {
324
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_one", ret);
325
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
326
0
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
327
0
        return ret;
328
0
    }
329
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
330
331
    /* Only mark the extension as OK when we're sure it is */
332
0
    ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK;
333
334
0
    return 0;
335
0
}
336
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
337
338
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
339
MBEDTLS_CHECK_RETURN_CRITICAL
340
static int ssl_parse_max_fragment_length_ext(mbedtls_ssl_context *ssl,
341
                                             const unsigned char *buf,
342
                                             size_t len)
343
0
{
344
0
    if (len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID) {
345
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
346
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
347
0
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
348
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
349
0
    }
350
351
0
    ssl->session_negotiate->mfl_code = buf[0];
352
353
0
    return 0;
354
0
}
355
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
356
357
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
358
MBEDTLS_CHECK_RETURN_CRITICAL
359
static int ssl_parse_cid_ext(mbedtls_ssl_context *ssl,
360
                             const unsigned char *buf,
361
                             size_t len)
362
{
363
    size_t peer_cid_len;
364
365
    /* CID extension only makes sense in DTLS */
366
    if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
367
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
368
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
369
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
370
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
371
    }
372
373
    /*
374
     *   struct {
375
     *      opaque cid<0..2^8-1>;
376
     *   } ConnectionId;
377
     */
378
379
    if (len < 1) {
380
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
381
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
382
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
383
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
384
    }
385
386
    peer_cid_len = *buf++;
387
    len--;
388
389
    if (len != peer_cid_len) {
390
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
391
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
392
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
393
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
394
    }
395
396
    /* Ignore CID if the user has disabled its use. */
397
    if (ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED) {
398
        /* Leave ssl->handshake->cid_in_use in its default
399
         * value of MBEDTLS_SSL_CID_DISABLED. */
400
        MBEDTLS_SSL_DEBUG_MSG(3, ("Client sent CID extension, but CID disabled"));
401
        return 0;
402
    }
403
404
    if (peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX) {
405
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
406
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
407
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
408
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
409
    }
410
411
    ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
412
    ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
413
    memcpy(ssl->handshake->peer_cid, buf, peer_cid_len);
414
415
    MBEDTLS_SSL_DEBUG_MSG(3, ("Use of CID extension negotiated"));
416
    MBEDTLS_SSL_DEBUG_BUF(3, "Client CID", buf, peer_cid_len);
417
418
    return 0;
419
}
420
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
421
422
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
423
MBEDTLS_CHECK_RETURN_CRITICAL
424
static int ssl_parse_encrypt_then_mac_ext(mbedtls_ssl_context *ssl,
425
                                          const unsigned char *buf,
426
                                          size_t len)
427
{
428
    if (len != 0) {
429
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
430
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
431
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
432
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
433
    }
434
435
    ((void) buf);
436
437
    if (ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED) {
438
        ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
439
    }
440
441
    return 0;
442
}
443
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
444
445
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
446
MBEDTLS_CHECK_RETURN_CRITICAL
447
static int ssl_parse_extended_ms_ext(mbedtls_ssl_context *ssl,
448
                                     const unsigned char *buf,
449
                                     size_t len)
450
{
451
    if (len != 0) {
452
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
453
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
454
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
455
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
456
    }
457
458
    ((void) buf);
459
460
    if (ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED) {
461
        ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
462
    }
463
464
    return 0;
465
}
466
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
467
468
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
469
MBEDTLS_CHECK_RETURN_CRITICAL
470
static int ssl_parse_session_ticket_ext(mbedtls_ssl_context *ssl,
471
                                        unsigned char *buf,
472
                                        size_t len)
473
{
474
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
475
    mbedtls_ssl_session session;
476
477
    mbedtls_ssl_session_init(&session);
478
479
    if (ssl->conf->f_ticket_parse == NULL ||
480
        ssl->conf->f_ticket_write == NULL) {
481
        return 0;
482
    }
483
484
    /* Remember the client asked us to send a new ticket */
485
    ssl->handshake->new_session_ticket = 1;
486
487
    MBEDTLS_SSL_DEBUG_MSG(3, ("ticket length: %" MBEDTLS_PRINTF_SIZET, len));
488
489
    if (len == 0) {
490
        return 0;
491
    }
492
493
#if defined(MBEDTLS_SSL_RENEGOTIATION)
494
    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
495
        MBEDTLS_SSL_DEBUG_MSG(3, ("ticket rejected: renegotiating"));
496
        return 0;
497
    }
498
#endif /* MBEDTLS_SSL_RENEGOTIATION */
499
500
    /*
501
     * Failures are ok: just ignore the ticket and proceed.
502
     */
503
    if ((ret = ssl->conf->f_ticket_parse(ssl->conf->p_ticket, &session,
504
                                         buf, len)) != 0) {
505
        mbedtls_ssl_session_free(&session);
506
507
        if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
508
            MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is not authentic"));
509
        } else if (ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) {
510
            MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is expired"));
511
        } else {
512
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_ticket_parse", ret);
513
        }
514
515
        return 0;
516
    }
517
518
    /*
519
     * Keep the session ID sent by the client, since we MUST send it back to
520
     * inform them we're accepting the ticket  (RFC 5077 section 3.4)
521
     */
522
    session.id_len = ssl->session_negotiate->id_len;
523
    memcpy(&session.id, ssl->session_negotiate->id, session.id_len);
524
525
    mbedtls_ssl_session_free(ssl->session_negotiate);
526
    memcpy(ssl->session_negotiate, &session, sizeof(mbedtls_ssl_session));
527
528
    /* Zeroize instead of free as we copied the content */
529
    mbedtls_platform_zeroize(&session, sizeof(mbedtls_ssl_session));
530
531
    MBEDTLS_SSL_DEBUG_MSG(3, ("session successfully restored from ticket"));
532
533
    ssl->handshake->resume = 1;
534
535
    /* Don't send a new ticket after all, this one is OK */
536
    ssl->handshake->new_session_ticket = 0;
537
538
    return 0;
539
}
540
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
541
542
#if defined(MBEDTLS_SSL_DTLS_SRTP)
543
MBEDTLS_CHECK_RETURN_CRITICAL
544
static int ssl_parse_use_srtp_ext(mbedtls_ssl_context *ssl,
545
                                  const unsigned char *buf,
546
                                  size_t len)
547
{
548
    mbedtls_ssl_srtp_profile client_protection = MBEDTLS_TLS_SRTP_UNSET;
549
    size_t i, j;
550
    size_t profile_length;
551
    uint16_t mki_length;
552
    /*! 2 bytes for profile length and 1 byte for mki len */
553
    const size_t size_of_lengths = 3;
554
555
    /* If use_srtp is not configured, just ignore the extension */
556
    if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
557
        (ssl->conf->dtls_srtp_profile_list == NULL) ||
558
        (ssl->conf->dtls_srtp_profile_list_len == 0)) {
559
        return 0;
560
    }
561
562
    /* RFC5764 section 4.1.1
563
     * uint8 SRTPProtectionProfile[2];
564
     *
565
     * struct {
566
     *   SRTPProtectionProfiles SRTPProtectionProfiles;
567
     *   opaque srtp_mki<0..255>;
568
     * } UseSRTPData;
569
570
     * SRTPProtectionProfile SRTPProtectionProfiles<2..2^16-1>;
571
     */
572
573
    /*
574
     * Min length is 5: at least one protection profile(2 bytes)
575
     *                  and length(2 bytes) + srtp_mki length(1 byte)
576
     * Check here that we have at least 2 bytes of protection profiles length
577
     * and one of srtp_mki length
578
     */
579
    if (len < size_of_lengths) {
580
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
581
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
582
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
583
    }
584
585
    ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
586
587
    /* first 2 bytes are protection profile length(in bytes) */
588
    profile_length = (buf[0] << 8) | buf[1];
589
    buf += 2;
590
591
    /* The profile length cannot be bigger than input buffer size - lengths fields */
592
    if (profile_length > len - size_of_lengths ||
593
        profile_length % 2 != 0) { /* profiles are 2 bytes long, so the length must be even */
594
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
595
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
596
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
597
    }
598
    /*
599
     * parse the extension list values are defined in
600
     * http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
601
     */
602
    for (j = 0; j < profile_length; j += 2) {
603
        uint16_t protection_profile_value = buf[j] << 8 | buf[j + 1];
604
        client_protection = mbedtls_ssl_check_srtp_profile_value(protection_profile_value);
605
606
        if (client_protection != MBEDTLS_TLS_SRTP_UNSET) {
607
            MBEDTLS_SSL_DEBUG_MSG(3, ("found srtp profile: %s",
608
                                      mbedtls_ssl_get_srtp_profile_as_string(
609
                                          client_protection)));
610
        } else {
611
            continue;
612
        }
613
        /* check if suggested profile is in our list */
614
        for (i = 0; i < ssl->conf->dtls_srtp_profile_list_len; i++) {
615
            if (client_protection == ssl->conf->dtls_srtp_profile_list[i]) {
616
                ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
617
                MBEDTLS_SSL_DEBUG_MSG(3, ("selected srtp profile: %s",
618
                                          mbedtls_ssl_get_srtp_profile_as_string(
619
                                              client_protection)));
620
                break;
621
            }
622
        }
623
        if (ssl->dtls_srtp_info.chosen_dtls_srtp_profile != MBEDTLS_TLS_SRTP_UNSET) {
624
            break;
625
        }
626
    }
627
    buf += profile_length; /* buf points to the mki length */
628
    mki_length = *buf;
629
    buf++;
630
631
    if (mki_length > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH ||
632
        mki_length + profile_length + size_of_lengths != len) {
633
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
634
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
635
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
636
    }
637
638
    /* Parse the mki only if present and mki is supported locally */
639
    if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED &&
640
        mki_length > 0) {
641
        ssl->dtls_srtp_info.mki_len = mki_length;
642
643
        memcpy(ssl->dtls_srtp_info.mki_value, buf, mki_length);
644
645
        MBEDTLS_SSL_DEBUG_BUF(3, "using mki",  ssl->dtls_srtp_info.mki_value,
646
                              ssl->dtls_srtp_info.mki_len);
647
    }
648
649
    return 0;
650
}
651
#endif /* MBEDTLS_SSL_DTLS_SRTP */
652
653
/*
654
 * Auxiliary functions for ServerHello parsing and related actions
655
 */
656
657
#if defined(MBEDTLS_X509_CRT_PARSE_C)
658
/*
659
 * Return 0 if the given key uses one of the acceptable curves, -1 otherwise
660
 */
661
#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
662
MBEDTLS_CHECK_RETURN_CRITICAL
663
static int ssl_check_key_curve(mbedtls_pk_context *pk,
664
                               uint16_t *curves_tls_id)
665
0
{
666
0
    uint16_t *curr_tls_id = curves_tls_id;
667
0
    mbedtls_ecp_group_id grp_id = mbedtls_pk_get_ec_group_id(pk);
668
0
    mbedtls_ecp_group_id curr_grp_id;
669
670
0
    while (*curr_tls_id != 0) {
671
0
        curr_grp_id = mbedtls_ssl_get_ecp_group_id_from_tls_id(*curr_tls_id);
672
0
        if (curr_grp_id == grp_id) {
673
0
            return 0;
674
0
        }
675
0
        curr_tls_id++;
676
0
    }
677
678
0
    return -1;
679
0
}
680
#endif /* MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED */
681
682
/*
683
 * Try picking a certificate for this ciphersuite,
684
 * return 0 on success and -1 on failure.
685
 */
686
MBEDTLS_CHECK_RETURN_CRITICAL
687
static int ssl_pick_cert(mbedtls_ssl_context *ssl,
688
                         const mbedtls_ssl_ciphersuite_t *ciphersuite_info)
689
0
{
690
0
    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
0
    mbedtls_pk_type_t pk_alg =
698
0
        mbedtls_ssl_get_ciphersuite_sig_pk_alg(ciphersuite_info);
699
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
700
0
    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
0
    list = ssl->conf->key_cert;
708
709
0
    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
0
    pk_alg_is_none = (pk_alg == MBEDTLS_PK_NONE);
714
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
715
0
    if (pk_alg_is_none) {
716
0
        return 0;
717
0
    }
718
719
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite requires certificate"));
720
721
0
    if (list == NULL) {
722
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("server has no certificate"));
723
0
        return -1;
724
0
    }
725
726
0
    for (cur = list; cur != NULL; cur = cur->next) {
727
0
        flags = 0;
728
0
        MBEDTLS_SSL_DEBUG_CRT(3, "candidate certificate chain, certificate",
729
0
                              cur->cert);
730
731
0
        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
0
        key_type_matches = mbedtls_pk_can_do(&cur->cert->pk, pk_alg);
744
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
745
0
        if (!key_type_matches) {
746
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: key type"));
747
0
            continue;
748
0
        }
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
0
        if (mbedtls_ssl_check_cert_usage(cur->cert, ciphersuite_info,
759
0
                                         MBEDTLS_SSL_IS_SERVER, &flags) != 0) {
760
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: "
761
0
                                      "(extended) key usage extension"));
762
0
            continue;
763
0
        }
764
765
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
766
0
        if (pk_alg == MBEDTLS_PK_ECDSA &&
767
0
            ssl_check_key_curve(&cur->cert->pk,
768
0
                                ssl->handshake->curves_tls_id) != 0) {
769
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: elliptic curve"));
770
0
            continue;
771
0
        }
772
0
#endif
773
774
        /* If we get there, we got a winner */
775
0
        break;
776
0
    }
777
778
    /* Do not update ssl->handshake->key_cert unless there is a match */
779
0
    if (cur != NULL) {
780
0
        ssl->handshake->key_cert = cur;
781
0
        MBEDTLS_SSL_DEBUG_CRT(3, "selected certificate chain, certificate",
782
0
                              ssl->handshake->key_cert->cert);
783
0
        return 0;
784
0
    }
785
786
0
    return -1;
787
0
}
788
#endif /* MBEDTLS_X509_CRT_PARSE_C */
789
790
/*
791
 * Check if a given ciphersuite is suitable for use with our config/keys/etc
792
 * Sets ciphersuite_info only if the suite matches.
793
 */
794
MBEDTLS_CHECK_RETURN_CRITICAL
795
static int ssl_ciphersuite_match(mbedtls_ssl_context *ssl, int suite_id,
796
                                 const mbedtls_ssl_ciphersuite_t **ciphersuite_info)
797
0
{
798
0
    const mbedtls_ssl_ciphersuite_t *suite_info;
799
800
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
801
0
    mbedtls_pk_type_t sig_type;
802
0
#endif
803
804
0
    suite_info = mbedtls_ssl_ciphersuite_from_id(suite_id);
805
0
    if (suite_info == NULL) {
806
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
807
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
808
0
    }
809
810
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("trying ciphersuite: %#04x (%s)",
811
0
                              (unsigned int) suite_id, suite_info->name));
812
813
0
    if (suite_info->min_tls_version > ssl->tls_version ||
814
0
        suite_info->max_tls_version < ssl->tls_version) {
815
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: version"));
816
0
        return 0;
817
0
    }
818
819
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
820
0
    if (suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
821
0
        (ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK) == 0) {
822
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: ecjpake "
823
0
                                  "not configured or ext missing"));
824
0
        return 0;
825
0
    }
826
0
#endif
827
828
829
0
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
830
0
    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
831
0
    if (mbedtls_ssl_ciphersuite_uses_ec(suite_info) &&
832
0
        (ssl->handshake->curves_tls_id == NULL ||
833
0
         ssl->handshake->curves_tls_id[0] == 0)) {
834
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: "
835
0
                                  "no common elliptic curve"));
836
0
        return 0;
837
0
    }
838
0
#endif
839
840
0
#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
0
    if (mbedtls_ssl_ciphersuite_uses_psk(suite_info) &&
844
0
        ssl_conf_has_psk_or_cb(ssl->conf) == 0) {
845
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: no pre-shared key"));
846
0
        return 0;
847
0
    }
848
0
#endif
849
850
0
#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
0
    if (ssl_pick_cert(ssl, suite_info) != 0) {
859
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: "
860
0
                                  "no suitable certificate"));
861
0
        return 0;
862
0
    }
863
0
#endif
864
865
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
866
    /* If the ciphersuite requires signing, check whether
867
     * a suitable hash algorithm is present. */
868
0
    sig_type = mbedtls_ssl_get_ciphersuite_sig_alg(suite_info);
869
0
    if (sig_type != MBEDTLS_PK_NONE &&
870
0
        mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
871
0
            ssl, mbedtls_ssl_sig_from_pk_alg(sig_type)) == MBEDTLS_SSL_HASH_NONE) {
872
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: no suitable hash algorithm "
873
0
                                  "for signature algorithm %u", (unsigned) sig_type));
874
0
        return 0;
875
0
    }
876
877
0
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
878
879
0
    *ciphersuite_info = suite_info;
880
0
    return 0;
881
0
}
882
883
/* This function doesn't alert on errors that happen early during
884
   ClientHello parsing because they might indicate that the client is
885
   not talking SSL/TLS at all and would not understand our alert. */
886
MBEDTLS_CHECK_RETURN_CRITICAL
887
static int ssl_parse_client_hello(mbedtls_ssl_context *ssl)
888
10.1k
{
889
10.1k
    int ret, got_common_suite;
890
10.1k
    size_t i, j;
891
10.1k
    size_t ciph_offset, comp_offset, ext_offset;
892
10.1k
    size_t msg_len, ciph_len, sess_len, comp_len, ext_len;
893
10.1k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
894
10.1k
    size_t cookie_offset, cookie_len;
895
10.1k
#endif
896
10.1k
    unsigned char *buf, *p, *ext;
897
#if defined(MBEDTLS_SSL_RENEGOTIATION)
898
    int renegotiation_info_seen = 0;
899
#endif
900
10.1k
    int handshake_failure = 0;
901
10.1k
    const int *ciphersuites;
902
10.1k
    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
10.1k
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
908
10.1k
    int sig_hash_alg_ext_present = 0;
909
10.1k
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
910
911
10.1k
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client hello"));
912
913
10.1k
    int renegotiating;
914
915
10.1k
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
916
10.1k
read_record_header:
917
10.1k
#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
10.1k
    renegotiating = 0;
927
#if defined(MBEDTLS_SSL_RENEGOTIATION)
928
    renegotiating = (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE);
929
#endif
930
10.1k
    if (!renegotiating && !ssl->keep_current_message) {
931
10.1k
        if ((ret = mbedtls_ssl_fetch_input(ssl, 5)) != 0) {
932
            /* No alert on a read error. */
933
5.26k
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
934
5.26k
            return ret;
935
5.26k
        }
936
10.1k
    }
937
938
4.84k
    buf = ssl->in_hdr;
939
940
4.84k
    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
4.84k
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, message type: %d",
952
4.84k
                              buf[0]));
953
954
4.84k
    if (buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE) {
955
381
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
956
381
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
957
381
    }
958
959
4.46k
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, message len.: %d",
960
4.46k
                              MBEDTLS_GET_UINT16_BE(ssl->in_len, 0)));
961
962
4.46k
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, protocol version: [%d:%d]",
963
4.46k
                              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
4.46k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
968
4.46k
    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
4.46k
        ) {
973
        /* Epoch should be 0 for initial handshakes */
974
4.46k
        if (ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0) {
975
2.60k
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
976
2.60k
            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
977
2.60k
        }
978
979
1.85k
        memcpy(&ssl->cur_out_ctr[2], ssl->in_ctr + 2,
980
1.85k
               sizeof(ssl->cur_out_ctr) - 2);
981
982
1.85k
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
983
1.85k
        if (mbedtls_ssl_dtls_replay_check(ssl) != 0) {
984
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("replayed record, discarding"));
985
0
            ssl->next_record_offset = 0;
986
0
            ssl->in_left = 0;
987
0
            goto read_record_header;
988
0
        }
989
990
        /* No MAC to check yet, so we can update right now */
991
1.85k
        mbedtls_ssl_dtls_replay_update(ssl);
992
1.85k
#endif
993
1.85k
    }
994
1.85k
#endif /* MBEDTLS_SSL_PROTO_DTLS */
995
996
1.85k
    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
1.85k
    {
1005
1.85k
        if (ssl->keep_current_message) {
1006
0
            ssl->keep_current_message = 0;
1007
1.85k
        } else {
1008
1.85k
            if (msg_len > MBEDTLS_SSL_IN_CONTENT_LEN) {
1009
677
                MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1010
677
                return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1011
677
            }
1012
1013
1.18k
            if ((ret = mbedtls_ssl_fetch_input(ssl,
1014
1.18k
                                               mbedtls_ssl_in_hdr_len(ssl) + msg_len)) != 0) {
1015
855
                MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
1016
855
                return ret;
1017
855
            }
1018
1019
            /* Done reading this record, get ready for the next one */
1020
325
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1021
325
            if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1022
325
                ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len(ssl);
1023
325
            } else
1024
0
#endif
1025
0
            ssl->in_left = 0;
1026
325
        }
1027
1.85k
    }
1028
1029
325
    buf = ssl->in_msg;
1030
1031
325
    MBEDTLS_SSL_DEBUG_BUF(4, "record contents", buf, msg_len);
1032
1033
325
    ret = ssl->handshake->update_checksum(ssl, buf, msg_len);
1034
325
    if (0 != ret) {
1035
0
        MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
1036
0
        return ret;
1037
0
    }
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
325
    if (msg_len < mbedtls_ssl_hs_hdr_len(ssl)) {
1048
325
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1049
325
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1050
325
    }
1051
1052
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, handshake type: %d", buf[0]));
1053
1054
0
    if (buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO) {
1055
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1056
0
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
1057
0
    }
1058
0
    {
1059
0
        size_t handshake_len = MBEDTLS_GET_UINT24_BE(buf, 1);
1060
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, handshake len.: %u",
1061
0
                                  (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
0
        if (buf[1] != 0) {
1066
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message: %u != 0",
1067
0
                                      (unsigned) buf[1]));
1068
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1069
0
        }
1070
1071
        /* We don't support fragmentation of ClientHello (yet?) */
1072
0
        if (msg_len != mbedtls_ssl_hs_hdr_len(ssl) + handshake_len) {
1073
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message: %u != %u + %u",
1074
0
                                      (unsigned) msg_len,
1075
0
                                      (unsigned) mbedtls_ssl_hs_hdr_len(ssl),
1076
0
                                      (unsigned) handshake_len));
1077
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1078
0
        }
1079
0
    }
1080
1081
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1082
0
    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
0
        {
1102
0
            unsigned int cli_msg_seq = (unsigned int) MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
1103
0
            ssl->handshake->out_msg_seq = cli_msg_seq;
1104
0
            ssl->handshake->in_msg_seq  = cli_msg_seq + 1;
1105
0
        }
1106
0
        {
1107
            /*
1108
             * For now we don't support fragmentation, so make sure
1109
             * fragment_offset == 0 and fragment_length == length
1110
             */
1111
0
            size_t fragment_offset, fragment_length, length;
1112
0
            fragment_offset = MBEDTLS_GET_UINT24_BE(ssl->in_msg, 6);
1113
0
            fragment_length = MBEDTLS_GET_UINT24_BE(ssl->in_msg, 9);
1114
0
            length = MBEDTLS_GET_UINT24_BE(ssl->in_msg, 1);
1115
0
            MBEDTLS_SSL_DEBUG_MSG(
1116
0
                4, ("fragment_offset=%u fragment_length=%u length=%u",
1117
0
                    (unsigned) fragment_offset, (unsigned) fragment_length,
1118
0
                    (unsigned) length));
1119
0
            if (fragment_offset != 0 || length != fragment_length) {
1120
0
                MBEDTLS_SSL_DEBUG_MSG(1, ("ClientHello fragmentation not supported"));
1121
0
                return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1122
0
            }
1123
0
        }
1124
0
    }
1125
0
#endif /* MBEDTLS_SSL_PROTO_DTLS */
1126
1127
0
    buf += mbedtls_ssl_hs_hdr_len(ssl);
1128
0
    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
0
    if (msg_len < 38) {
1152
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1153
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1154
0
    }
1155
1156
    /*
1157
     * Check and save the protocol version
1158
     */
1159
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, version", buf, 2);
1160
1161
0
    ssl->tls_version = (mbedtls_ssl_protocol_version) mbedtls_ssl_read_version(buf,
1162
0
                                                                               ssl->conf->transport);
1163
0
    ssl->session_negotiate->tls_version = ssl->tls_version;
1164
0
    ssl->session_negotiate->endpoint = ssl->conf->endpoint;
1165
1166
0
    if (ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_2) {
1167
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("server only supports TLS 1.2"));
1168
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1169
0
                                       MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1170
0
        return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1171
0
    }
1172
1173
    /*
1174
     * Save client random (inc. Unix time)
1175
     */
1176
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, random bytes", buf + 2, 32);
1177
1178
0
    memcpy(ssl->handshake->randbytes, buf + 2, 32);
1179
1180
    /*
1181
     * Check the session ID length and save session ID
1182
     */
1183
0
    sess_len = buf[34];
1184
1185
0
    if (sess_len > sizeof(ssl->session_negotiate->id) ||
1186
0
        sess_len + 34 + 2 > msg_len) { /* 2 for cipherlist length field */
1187
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1188
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1189
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1190
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1191
0
    }
1192
1193
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, session id", buf + 35, sess_len);
1194
1195
0
    ssl->session_negotiate->id_len = sess_len;
1196
0
    memset(ssl->session_negotiate->id, 0,
1197
0
           sizeof(ssl->session_negotiate->id));
1198
0
    memcpy(ssl->session_negotiate->id, buf + 35,
1199
0
           ssl->session_negotiate->id_len);
1200
1201
    /*
1202
     * Check the cookie length and content
1203
     */
1204
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1205
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1206
0
        cookie_offset = 35 + sess_len;
1207
0
        cookie_len = buf[cookie_offset];
1208
1209
0
        if (cookie_offset + 1 + cookie_len + 2 > msg_len) {
1210
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1211
0
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1212
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1213
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1214
0
        }
1215
1216
0
        MBEDTLS_SSL_DEBUG_BUF(3, "client hello, cookie",
1217
0
                              buf + cookie_offset + 1, cookie_len);
1218
1219
0
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
1220
0
        if (ssl->conf->f_cookie_check != NULL
1221
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1222
            && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
1223
#endif
1224
0
            ) {
1225
0
            if (ssl->conf->f_cookie_check(ssl->conf->p_cookie,
1226
0
                                          buf + cookie_offset + 1, cookie_len,
1227
0
                                          ssl->cli_id, ssl->cli_id_len) != 0) {
1228
0
                MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification failed"));
1229
0
                ssl->handshake->cookie_verify_result = 1;
1230
0
            } else {
1231
0
                MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification passed"));
1232
0
                ssl->handshake->cookie_verify_result = 0;
1233
0
            }
1234
0
        } else
1235
0
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
1236
0
        {
1237
            /* We know we didn't send a cookie, so it should be empty */
1238
0
            if (cookie_len != 0) {
1239
                /* This may be an attacker's probe, so don't send an alert */
1240
0
                MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1241
0
                return MBEDTLS_ERR_SSL_DECODE_ERROR;
1242
0
            }
1243
1244
0
            MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification skipped"));
1245
0
        }
1246
1247
        /*
1248
         * Check the ciphersuitelist length (will be parsed later)
1249
         */
1250
0
        ciph_offset = cookie_offset + 1 + cookie_len;
1251
0
    } else
1252
0
#endif /* MBEDTLS_SSL_PROTO_DTLS */
1253
0
    ciph_offset = 35 + sess_len;
1254
1255
0
    ciph_len = MBEDTLS_GET_UINT16_BE(buf, ciph_offset);
1256
1257
0
    if (ciph_len < 2 ||
1258
0
        ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */
1259
0
        (ciph_len % 2) != 0) {
1260
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1261
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1262
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1263
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1264
0
    }
1265
1266
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, ciphersuitelist",
1267
0
                          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
0
    comp_offset = ciph_offset + 2 + ciph_len;
1276
1277
0
    comp_len = buf[comp_offset];
1278
1279
0
    if (comp_len < 1 ||
1280
0
        comp_len > 16 ||
1281
0
        comp_len + comp_offset + 1 > msg_len) {
1282
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1283
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1284
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1285
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1286
0
    }
1287
1288
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, compression",
1289
0
                          buf + comp_offset + 1, comp_len);
1290
1291
    /*
1292
     * Check the extension length
1293
     */
1294
0
    ext_offset = comp_offset + 1 + comp_len;
1295
0
    if (msg_len > ext_offset) {
1296
0
        if (msg_len < ext_offset + 2) {
1297
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1298
0
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1299
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1300
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1301
0
        }
1302
1303
0
        ext_len = MBEDTLS_GET_UINT16_BE(buf, ext_offset);
1304
1305
0
        if (msg_len != ext_offset + 2 + ext_len) {
1306
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1307
0
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1308
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1309
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1310
0
        }
1311
0
    } else {
1312
0
        ext_len = 0;
1313
0
    }
1314
1315
0
    ext = buf + ext_offset + 2;
1316
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello extensions", ext, ext_len);
1317
1318
0
    while (ext_len != 0) {
1319
0
        unsigned int ext_id;
1320
0
        unsigned int ext_size;
1321
0
        if (ext_len < 4) {
1322
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1323
0
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1324
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1325
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1326
0
        }
1327
0
        ext_id   = MBEDTLS_GET_UINT16_BE(ext, 0);
1328
0
        ext_size = MBEDTLS_GET_UINT16_BE(ext, 2);
1329
1330
0
        if (ext_size + 4 > ext_len) {
1331
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1332
0
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1333
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1334
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1335
0
        }
1336
0
        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
0
            case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1349
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found renegotiation extension"));
1350
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1351
                renegotiation_info_seen = 1;
1352
#endif
1353
1354
0
                ret = ssl_parse_renegotiation_info(ssl, ext + 4, ext_size);
1355
0
                if (ret != 0) {
1356
0
                    return ret;
1357
0
                }
1358
0
                break;
1359
1360
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1361
0
            case MBEDTLS_TLS_EXT_SIG_ALG:
1362
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found signature_algorithms extension"));
1363
1364
0
                ret = mbedtls_ssl_parse_sig_alg_ext(ssl, ext + 4, ext + 4 + ext_size);
1365
0
                if (ret != 0) {
1366
0
                    return ret;
1367
0
                }
1368
1369
0
                sig_hash_alg_ext_present = 1;
1370
0
                break;
1371
0
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1372
1373
0
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
1374
0
                defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
1375
0
                defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1376
0
            case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
1377
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found supported elliptic curves extension"));
1378
1379
0
                ret = ssl_parse_supported_groups_ext(ssl, ext + 4, ext_size);
1380
0
                if (ret != 0) {
1381
0
                    return ret;
1382
0
                }
1383
0
                break;
1384
1385
0
            case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1386
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found supported point formats extension"));
1387
0
                ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
1388
1389
0
                ret = ssl_parse_supported_point_formats(ssl, ext + 4, ext_size);
1390
0
                if (ret != 0) {
1391
0
                    return ret;
1392
0
                }
1393
0
                break;
1394
0
#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
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1399
0
            case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1400
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found ecjpake kkpp extension"));
1401
1402
0
                ret = ssl_parse_ecjpake_kkpp(ssl, ext + 4, ext_size);
1403
0
                if (ret != 0) {
1404
0
                    return ret;
1405
0
                }
1406
0
                break;
1407
0
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1408
1409
0
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1410
0
            case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1411
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found max fragment length extension"));
1412
1413
0
                ret = ssl_parse_max_fragment_length_ext(ssl, ext + 4, ext_size);
1414
0
                if (ret != 0) {
1415
0
                    return ret;
1416
0
                }
1417
0
                break;
1418
0
#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
0
            default:
1488
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("unknown extension found: %u (ignoring)",
1489
0
                                          ext_id));
1490
0
        }
1491
1492
0
        ext_len -= 4 + ext_size;
1493
0
        ext += 4 + ext_size;
1494
0
    }
1495
1496
0
#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
0
    if (!sig_hash_alg_ext_present) {
1503
0
        uint16_t *received_sig_algs = ssl->handshake->received_sig_algs;
1504
0
        const uint16_t default_sig_algs[] = {
1505
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
1506
0
            MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG(MBEDTLS_SSL_SIG_ECDSA,
1507
0
                                               MBEDTLS_SSL_HASH_SHA1),
1508
0
#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
0
            MBEDTLS_TLS_SIG_NONE
1514
0
        };
1515
1516
0
        MBEDTLS_STATIC_ASSERT(sizeof(default_sig_algs) / sizeof(default_sig_algs[0])
1517
0
                              <= MBEDTLS_RECEIVED_SIG_ALGS_SIZE,
1518
0
                              "default_sig_algs is too big");
1519
1520
0
        memcpy(received_sig_algs, default_sig_algs, sizeof(default_sig_algs));
1521
0
    }
1522
1523
0
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1524
1525
    /*
1526
     * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1527
     */
1528
0
    for (i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2) {
1529
0
        if (p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO) {
1530
0
            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
0
            ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
1541
0
            break;
1542
0
        }
1543
0
    }
1544
1545
    /*
1546
     * Renegotiation security checks
1547
     */
1548
0
    if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1549
0
        ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE) {
1550
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation, breaking off handshake"));
1551
0
        handshake_failure = 1;
1552
0
    }
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
0
    if (handshake_failure == 1) {
1573
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1574
0
                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1575
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1576
0
    }
1577
1578
    /*
1579
     * Server certification selection (after processing TLS extensions)
1580
     */
1581
0
    if (ssl->conf->f_cert_cb && (ret = ssl->conf->f_cert_cb(ssl)) != 0) {
1582
0
        MBEDTLS_SSL_DEBUG_RET(1, "f_cert_cb", ret);
1583
0
        return ret;
1584
0
    }
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
0
    got_common_suite = 0;
1597
0
    ciphersuites = ssl->conf->ciphersuite_list;
1598
0
    ciphersuite_info = NULL;
1599
1600
0
    if (ssl->conf->respect_cli_pref == MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_CLIENT) {
1601
0
        for (j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2) {
1602
0
            for (i = 0; ciphersuites[i] != 0; i++) {
1603
0
                if (MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i]) {
1604
0
                    continue;
1605
0
                }
1606
1607
0
                got_common_suite = 1;
1608
1609
0
                if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
1610
0
                                                 &ciphersuite_info)) != 0) {
1611
0
                    return ret;
1612
0
                }
1613
1614
0
                if (ciphersuite_info != NULL) {
1615
0
                    goto have_ciphersuite;
1616
0
                }
1617
0
            }
1618
0
        }
1619
0
    } else {
1620
0
        for (i = 0; ciphersuites[i] != 0; i++) {
1621
0
            for (j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2) {
1622
0
                if (MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i]) {
1623
0
                    continue;
1624
0
                }
1625
1626
0
                got_common_suite = 1;
1627
1628
0
                if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
1629
0
                                                 &ciphersuite_info)) != 0) {
1630
0
                    return ret;
1631
0
                }
1632
1633
0
                if (ciphersuite_info != NULL) {
1634
0
                    goto have_ciphersuite;
1635
0
                }
1636
0
            }
1637
0
        }
1638
0
    }
1639
1640
0
    if (got_common_suite) {
1641
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got ciphersuites in common, "
1642
0
                                  "but none of them usable"));
1643
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1644
0
                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1645
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1646
0
    } else {
1647
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no ciphersuites in common"));
1648
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1649
0
                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1650
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1651
0
    }
1652
1653
0
have_ciphersuite:
1654
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %s", ciphersuite_info->name));
1655
1656
0
    ssl->session_negotiate->ciphersuite = ciphersuites[i];
1657
0
    ssl->handshake->ciphersuite_info = ciphersuite_info;
1658
1659
0
    ssl->state++;
1660
1661
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1662
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1663
0
        mbedtls_ssl_recv_flight_completed(ssl);
1664
0
    }
1665
0
#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
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client hello"));
1683
1684
0
    return 0;
1685
0
}
1686
1687
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1688
static 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)
1732
static 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)
1778
static 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)
1803
static 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
1826
static void ssl_write_renegotiation_ext(mbedtls_ssl_context *ssl,
1827
                                        unsigned char *buf,
1828
                                        size_t *olen)
1829
0
{
1830
0
    unsigned char *p = buf;
1831
1832
0
    if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION) {
1833
0
        *olen = 0;
1834
0
        return;
1835
0
    }
1836
1837
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, secure renegotiation extension"));
1838
1839
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_RENEGOTIATION_INFO, p, 0);
1840
0
    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
0
    {
1855
0
        *p++ = 0x00;
1856
0
        *p++ = 0x01;
1857
0
        *p++ = 0x00;
1858
0
    }
1859
1860
0
    *olen = (size_t) (p - buf);
1861
0
}
1862
1863
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1864
static void ssl_write_max_fragment_length_ext(mbedtls_ssl_context *ssl,
1865
                                              unsigned char *buf,
1866
                                              size_t *olen)
1867
0
{
1868
0
    unsigned char *p = buf;
1869
1870
0
    if (ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE) {
1871
0
        *olen = 0;
1872
0
        return;
1873
0
    }
1874
1875
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, max_fragment_length extension"));
1876
1877
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH, p, 0);
1878
0
    p += 2;
1879
1880
0
    *p++ = 0x00;
1881
0
    *p++ = 1;
1882
1883
0
    *p++ = ssl->session_negotiate->mfl_code;
1884
1885
0
    *olen = 5;
1886
0
}
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)
1892
static void ssl_write_supported_point_formats_ext(mbedtls_ssl_context *ssl,
1893
                                                  unsigned char *buf,
1894
                                                  size_t *olen)
1895
0
{
1896
0
    unsigned char *p = buf;
1897
0
    ((void) ssl);
1898
1899
0
    if ((ssl->handshake->cli_exts &
1900
0
         MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT) == 0) {
1901
0
        *olen = 0;
1902
0
        return;
1903
0
    }
1904
1905
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, supported_point_formats extension"));
1906
1907
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS, p, 0);
1908
0
    p += 2;
1909
1910
0
    *p++ = 0x00;
1911
0
    *p++ = 2;
1912
1913
0
    *p++ = 1;
1914
0
    *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
1915
1916
0
    *olen = 6;
1917
0
}
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)
1923
static void ssl_write_ecjpake_kkpp_ext(mbedtls_ssl_context *ssl,
1924
                                       unsigned char *buf,
1925
                                       size_t *olen)
1926
0
{
1927
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1928
0
    unsigned char *p = buf;
1929
0
    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
1930
0
    size_t kkpp_len;
1931
1932
0
    *olen = 0;
1933
1934
    /* Skip costly computation if not needed */
1935
0
    if (ssl->handshake->ciphersuite_info->key_exchange !=
1936
0
        MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1937
0
        return;
1938
0
    }
1939
1940
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, ecjpake kkpp extension"));
1941
1942
0
    if (end - p < 4) {
1943
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
1944
0
        return;
1945
0
    }
1946
1947
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ECJPAKE_KKPP, p, 0);
1948
0
    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
0
    ret = mbedtls_ecjpake_write_round_one(&ssl->handshake->ecjpake_ctx,
1962
0
                                          p + 2, (size_t) (end - p - 2), &kkpp_len,
1963
0
                                          ssl->conf->f_rng, ssl->conf->p_rng);
1964
0
    if (ret != 0) {
1965
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_one", ret);
1966
0
        return;
1967
0
    }
1968
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1969
1970
0
    MBEDTLS_PUT_UINT16_BE(kkpp_len, p, 0);
1971
0
    p += 2;
1972
1973
0
    *olen = kkpp_len + 4;
1974
0
}
1975
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1976
1977
#if defined(MBEDTLS_SSL_DTLS_SRTP) && defined(MBEDTLS_SSL_PROTO_DTLS)
1978
static 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)
2041
MBEDTLS_CHECK_RETURN_CRITICAL
2042
static int ssl_write_hello_verify_request(mbedtls_ssl_context *ssl)
2043
0
{
2044
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2045
0
    unsigned char *p = ssl->out_msg + 4;
2046
0
    unsigned char *cookie_len_byte;
2047
2048
0
    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
0
    mbedtls_ssl_write_version(p, ssl->conf->transport, ssl->tls_version);
2060
0
    MBEDTLS_SSL_DEBUG_BUF(3, "server version", p, 2);
2061
0
    p += 2;
2062
2063
    /* If we get here, f_cookie_check is not null */
2064
0
    if (ssl->conf->f_cookie_write == NULL) {
2065
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("inconsistent cookie callbacks"));
2066
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2067
0
    }
2068
2069
    /* Skip length byte until we know the length */
2070
0
    cookie_len_byte = p++;
2071
2072
0
    if ((ret = ssl->conf->f_cookie_write(ssl->conf->p_cookie,
2073
0
                                         &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN,
2074
0
                                         ssl->cli_id, ssl->cli_id_len)) != 0) {
2075
0
        MBEDTLS_SSL_DEBUG_RET(1, "f_cookie_write", ret);
2076
0
        return ret;
2077
0
    }
2078
2079
0
    *cookie_len_byte = (unsigned char) (p - (cookie_len_byte + 1));
2080
2081
0
    MBEDTLS_SSL_DEBUG_BUF(3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte);
2082
2083
0
    ssl->out_msglen  = (size_t) (p - ssl->out_msg);
2084
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2085
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST;
2086
2087
0
    ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT;
2088
2089
0
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
2090
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
2091
0
        return ret;
2092
0
    }
2093
2094
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
2095
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2096
0
        (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
2097
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
2098
0
        return ret;
2099
0
    }
2100
0
#endif /* MBEDTLS_SSL_PROTO_DTLS */
2101
2102
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write hello verify request"));
2103
2104
0
    return 0;
2105
0
}
2106
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */
2107
2108
static void ssl_handle_id_based_session_resumption(mbedtls_ssl_context *ssl)
2109
0
{
2110
0
    int ret;
2111
0
    mbedtls_ssl_session session_tmp;
2112
0
    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
0
    if (ssl->handshake->resume == 1) {
2117
0
        return;
2118
0
    }
2119
0
    if (session->id_len == 0) {
2120
0
        return;
2121
0
    }
2122
0
    if (ssl->conf->f_get_cache == NULL) {
2123
0
        return;
2124
0
    }
2125
#if defined(MBEDTLS_SSL_RENEGOTIATION)
2126
    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
2127
        return;
2128
    }
2129
#endif
2130
2131
0
    mbedtls_ssl_session_init(&session_tmp);
2132
2133
0
    ret = ssl->conf->f_get_cache(ssl->conf->p_cache,
2134
0
                                 session->id,
2135
0
                                 session->id_len,
2136
0
                                 &session_tmp);
2137
0
    if (ret != 0) {
2138
0
        goto exit;
2139
0
    }
2140
2141
0
    if (session->ciphersuite != session_tmp.ciphersuite) {
2142
        /* Mismatch between cached and negotiated session */
2143
0
        goto exit;
2144
0
    }
2145
2146
    /* Move semantics */
2147
0
    mbedtls_ssl_session_free(session);
2148
0
    *session = session_tmp;
2149
0
    memset(&session_tmp, 0, sizeof(session_tmp));
2150
2151
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("session successfully restored from cache"));
2152
0
    ssl->handshake->resume = 1;
2153
2154
0
exit:
2155
2156
0
    mbedtls_ssl_session_free(&session_tmp);
2157
0
}
2158
2159
MBEDTLS_CHECK_RETURN_CRITICAL
2160
static int ssl_write_server_hello(mbedtls_ssl_context *ssl)
2161
0
{
2162
#if defined(MBEDTLS_HAVE_TIME)
2163
    mbedtls_time_t t;
2164
#endif
2165
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2166
0
    size_t olen, ext_len = 0, n;
2167
0
    unsigned char *buf, *p;
2168
2169
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello"));
2170
2171
0
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2172
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2173
0
        ssl->handshake->cookie_verify_result != 0) {
2174
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("client hello was not authenticated"));
2175
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2176
2177
0
        return ssl_write_hello_verify_request(ssl);
2178
0
    }
2179
0
#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
0
    buf = ssl->out_msg;
2189
0
    p = buf + 4;
2190
2191
0
    mbedtls_ssl_write_version(p, ssl->conf->transport, ssl->tls_version);
2192
0
    p += 2;
2193
2194
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen version: [%d:%d]",
2195
0
                              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
0
    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 4)) != 0) {
2206
0
        return ret;
2207
0
    }
2208
2209
0
    p += 4;
2210
0
#endif /* MBEDTLS_HAVE_TIME */
2211
2212
0
    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 20)) != 0) {
2213
0
        return ret;
2214
0
    }
2215
0
    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
0
    {
2238
0
        if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 8)) != 0) {
2239
0
            return ret;
2240
0
        }
2241
0
    }
2242
0
    p += 8;
2243
2244
0
    memcpy(ssl->handshake->randbytes + 32, buf + 6, 32);
2245
2246
0
    MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes", buf + 6, 32);
2247
2248
0
    ssl_handle_id_based_session_resumption(ssl);
2249
2250
0
    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
0
        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
0
        {
2268
0
            ssl->session_negotiate->id_len = n = 32;
2269
0
            if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, ssl->session_negotiate->id,
2270
0
                                        n)) != 0) {
2271
0
                return ret;
2272
0
            }
2273
0
        }
2274
0
    } else {
2275
        /*
2276
         * Resuming a session
2277
         */
2278
0
        n = ssl->session_negotiate->id_len;
2279
0
        ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC;
2280
2281
0
        if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
2282
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
2283
0
            return ret;
2284
0
        }
2285
0
    }
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
0
    *p++ = (unsigned char) ssl->session_negotiate->id_len;
2296
0
    memcpy(p, ssl->session_negotiate->id, ssl->session_negotiate->id_len);
2297
0
    p += ssl->session_negotiate->id_len;
2298
2299
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n));
2300
0
    MBEDTLS_SSL_DEBUG_BUF(3,   "server hello, session id", buf + 39, n);
2301
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("%s session has been resumed",
2302
0
                              ssl->handshake->resume ? "a" : "no"));
2303
2304
0
    MBEDTLS_PUT_UINT16_BE(ssl->session_negotiate->ciphersuite, p, 0);
2305
0
    p += 2;
2306
0
    *p++ = MBEDTLS_BYTE_0(MBEDTLS_SSL_COMPRESS_NULL);
2307
2308
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen ciphersuite: %s",
2309
0
                              mbedtls_ssl_get_ciphersuite_name(ssl->session_negotiate->ciphersuite)));
2310
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, compress alg.: 0x%02X",
2311
0
                              (unsigned int) MBEDTLS_SSL_COMPRESS_NULL));
2312
2313
    /*
2314
     *  First write extensions, then the total length
2315
     */
2316
0
    ssl_write_renegotiation_ext(ssl, p + 2 + ext_len, &olen);
2317
0
    ext_len += olen;
2318
2319
0
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2320
0
    ssl_write_max_fragment_length_ext(ssl, p + 2 + ext_len, &olen);
2321
0
    ext_len += olen;
2322
0
#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
0
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
2345
0
    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
2346
0
    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2347
0
    const mbedtls_ssl_ciphersuite_t *suite =
2348
0
        mbedtls_ssl_ciphersuite_from_id(ssl->session_negotiate->ciphersuite);
2349
0
    if (suite != NULL && mbedtls_ssl_ciphersuite_uses_ec(suite)) {
2350
0
        ssl_write_supported_point_formats_ext(ssl, p + 2 + ext_len, &olen);
2351
0
        ext_len += olen;
2352
0
    }
2353
0
#endif
2354
2355
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2356
0
    ssl_write_ecjpake_kkpp_ext(ssl, p + 2 + ext_len, &olen);
2357
0
    ext_len += olen;
2358
0
#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
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, total extension length: %" MBEDTLS_PRINTF_SIZET,
2376
0
                              ext_len));
2377
2378
0
    if (ext_len > 0) {
2379
0
        MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
2380
0
        p += 2 + ext_len;
2381
0
    }
2382
2383
0
    ssl->out_msglen  = (size_t) (p - buf);
2384
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2385
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;
2386
2387
0
    ret = mbedtls_ssl_write_handshake_msg(ssl);
2388
2389
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2390
2391
0
    return ret;
2392
0
}
2393
2394
#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
2395
MBEDTLS_CHECK_RETURN_CRITICAL
2396
static 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 */
2413
MBEDTLS_CHECK_RETURN_CRITICAL
2414
static int ssl_write_certificate_request(mbedtls_ssl_context *ssl)
2415
0
{
2416
0
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2417
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2418
0
        ssl->handshake->ciphersuite_info;
2419
0
    uint16_t dn_size, total_dn_size; /* excluding length bytes */
2420
0
    size_t ct_len, sa_len; /* including length bytes */
2421
0
    unsigned char *buf, *p;
2422
0
    const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2423
0
    const mbedtls_x509_crt *crt;
2424
0
    int authmode;
2425
2426
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2427
2428
0
    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
0
    authmode = ssl->conf->authmode;
2436
2437
0
    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info) ||
2438
0
        authmode == MBEDTLS_SSL_VERIFY_NONE) {
2439
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
2440
0
        return 0;
2441
0
    }
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
0
    buf = ssl->out_msg;
2456
0
    p = buf + 4;
2457
2458
    /*
2459
     * Supported certificate types
2460
     *
2461
     *     ClientCertificateType certificate_types<1..2^8-1>;
2462
     *     enum { (255) } ClientCertificateType;
2463
     */
2464
0
    ct_len = 0;
2465
2466
#if defined(MBEDTLS_RSA_C)
2467
    p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
2468
#endif
2469
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
2470
0
    p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN;
2471
0
#endif
2472
2473
0
    p[0] = (unsigned char) ct_len++;
2474
0
    p += ct_len;
2475
2476
0
    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
0
    const uint16_t *sig_alg = mbedtls_ssl_get_sig_algs(ssl);
2492
0
    if (sig_alg == NULL) {
2493
0
        return MBEDTLS_ERR_SSL_BAD_CONFIG;
2494
0
    }
2495
2496
0
    for (; *sig_alg != MBEDTLS_TLS_SIG_NONE; sig_alg++) {
2497
0
        unsigned char hash = MBEDTLS_BYTE_1(*sig_alg);
2498
2499
0
        if (mbedtls_ssl_set_calc_verify_md(ssl, hash)) {
2500
0
            continue;
2501
0
        }
2502
0
        if (!mbedtls_ssl_sig_alg_is_supported(ssl, *sig_alg)) {
2503
0
            continue;
2504
0
        }
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
0
        sa_len += 2;
2510
0
        MBEDTLS_PUT_UINT16_BE(*sig_alg, p, sa_len);
2511
2512
0
    }
2513
2514
    /* Fill in list length. */
2515
0
    MBEDTLS_PUT_UINT16_BE(sa_len, p, 0);
2516
0
    sa_len += 2;
2517
0
    p += sa_len;
2518
2519
    /*
2520
     * DistinguishedName certificate_authorities<0..2^16-1>;
2521
     * opaque DistinguishedName<1..2^16-1>;
2522
     */
2523
0
    p += 2;
2524
2525
0
    total_dn_size = 0;
2526
2527
0
    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
0
#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
0
        if (ssl->conf->dn_hints != NULL) {
2540
0
            crt = ssl->conf->dn_hints;
2541
0
        } else
2542
0
#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
0
        crt = ssl->conf->ca_chain;
2549
2550
0
        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
0
            dn_size = (uint16_t) crt->subject_raw.len;
2554
2555
0
            if (end < p || (size_t) (end - p) < 2 + (size_t) dn_size) {
2556
0
                MBEDTLS_SSL_DEBUG_MSG(1, ("skipping CAs: buffer too short"));
2557
0
                break;
2558
0
            }
2559
2560
0
            MBEDTLS_PUT_UINT16_BE(dn_size, p, 0);
2561
0
            p += 2;
2562
0
            memcpy(p, crt->subject_raw.p, dn_size);
2563
0
            p += dn_size;
2564
2565
0
            MBEDTLS_SSL_DEBUG_BUF(3, "requested DN", p - dn_size, dn_size);
2566
2567
0
            total_dn_size += (unsigned short) (2 + dn_size);
2568
0
            crt = crt->next;
2569
0
        }
2570
0
    }
2571
2572
0
    ssl->out_msglen  = (size_t) (p - buf);
2573
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2574
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST;
2575
0
    MBEDTLS_PUT_UINT16_BE(total_dn_size, ssl->out_msg, 4 + ct_len + sa_len);
2576
2577
0
    ret = mbedtls_ssl_write_handshake_msg(ssl);
2578
2579
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate request"));
2580
2581
0
    return ret;
2582
0
}
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)
2588
MBEDTLS_CHECK_RETURN_CRITICAL
2589
static 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
2723
exit:
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 */
2730
MBEDTLS_CHECK_RETURN_CRITICAL
2731
static 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)
2761
MBEDTLS_CHECK_RETURN_CRITICAL
2762
static 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. */
2788
MBEDTLS_CHECK_RETURN_CRITICAL
2789
static int ssl_prepare_server_key_exchange(mbedtls_ssl_context *ssl,
2790
                                           size_t *signature_len)
2791
0
{
2792
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2793
0
        ssl->handshake->ciphersuite_info;
2794
2795
0
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED)
2796
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2797
0
    unsigned char *dig_signed = NULL;
2798
0
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
2799
0
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */
2800
2801
0
    (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
0
#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
0
    size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN - (size_t) (ssl->out_msg - ssl->out_buf);
2811
0
#endif
2812
0
#endif
2813
2814
0
    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
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2826
0
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
2827
0
        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
0
        size_t len = 0;
2867
2868
0
        ret = mbedtls_ecjpake_write_round_two(
2869
0
            &ssl->handshake->ecjpake_ctx,
2870
0
            ssl->out_msg + ssl->out_msglen,
2871
0
            MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
2872
0
            ssl->conf->f_rng, ssl->conf->p_rng);
2873
0
        if (ret != 0) {
2874
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_two", ret);
2875
0
            return ret;
2876
0
        }
2877
2878
0
        ssl->out_msglen += len;
2879
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
2880
0
    }
2881
0
#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
0
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
2953
0
    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
0
        uint16_t *curr_tls_id = ssl->handshake->curves_tls_id;
2963
0
        const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
2964
0
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2965
0
        size_t len = 0;
2966
2967
        /* Match our preference list against the offered curves */
2968
0
        if ((group_list == NULL) || (curr_tls_id == NULL)) {
2969
0
            return MBEDTLS_ERR_SSL_BAD_CONFIG;
2970
0
        }
2971
0
        for (; *group_list != 0; group_list++) {
2972
0
            for (curr_tls_id = ssl->handshake->curves_tls_id;
2973
0
                 *curr_tls_id != 0; curr_tls_id++) {
2974
0
                if (*curr_tls_id == *group_list) {
2975
0
                    goto curve_matching_done;
2976
0
                }
2977
0
            }
2978
0
        }
2979
2980
0
curve_matching_done:
2981
0
        if (*curr_tls_id == 0) {
2982
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("no matching curve for ECDHE"));
2983
0
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2984
0
        }
2985
2986
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("ECDHE curve: %s",
2987
0
                                  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
0
        mbedtls_ecp_group_id curr_grp_id =
3073
0
            mbedtls_ssl_get_ecp_group_id_from_tls_id(*curr_tls_id);
3074
3075
0
        if ((ret = mbedtls_ecdh_setup(&ssl->handshake->ecdh_ctx,
3076
0
                                      curr_grp_id)) != 0) {
3077
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecp_group_load", ret);
3078
0
            return ret;
3079
0
        }
3080
3081
0
        if ((ret = mbedtls_ecdh_make_params(
3082
0
                 &ssl->handshake->ecdh_ctx, &len,
3083
0
                 ssl->out_msg + ssl->out_msglen,
3084
0
                 MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
3085
0
                 ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3086
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_make_params", ret);
3087
0
            return ret;
3088
0
        }
3089
3090
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3091
0
                               MBEDTLS_DEBUG_ECDH_Q);
3092
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3093
3094
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3095
0
        dig_signed = ssl->out_msg + ssl->out_msglen;
3096
0
#endif
3097
3098
0
        ssl->out_msglen += len;
3099
0
    }
3100
0
#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
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3109
0
    if (mbedtls_ssl_ciphersuite_uses_server_signature(ciphersuite_info)) {
3110
0
        if (dig_signed == NULL) {
3111
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3112
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3113
0
        }
3114
3115
0
        size_t dig_signed_len = (size_t) (ssl->out_msg + ssl->out_msglen - dig_signed);
3116
0
        size_t hashlen = 0;
3117
0
        unsigned char hash[MBEDTLS_MD_MAX_SIZE];
3118
3119
0
        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
0
        mbedtls_pk_type_t sig_alg =
3128
0
            mbedtls_ssl_get_ciphersuite_sig_pk_alg(ciphersuite_info);
3129
3130
0
        unsigned char sig_hash =
3131
0
            (unsigned char) mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
3132
0
                ssl, mbedtls_ssl_sig_from_pk_alg(sig_alg));
3133
3134
0
        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
0
        if (sig_alg == MBEDTLS_PK_NONE || md_alg == MBEDTLS_MD_NONE) {
3139
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3140
            /* (... because we choose a cipher suite
3141
             *      only if there is a matching hash.) */
3142
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3143
0
        }
3144
3145
0
        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
0
        if (md_alg != MBEDTLS_MD_NONE) {
3151
0
            ret = mbedtls_ssl_get_key_exchange_md_tls1_2(ssl, hash, &hashlen,
3152
0
                                                         dig_signed,
3153
0
                                                         dig_signed_len,
3154
0
                                                         md_alg);
3155
0
            if (ret != 0) {
3156
0
                return ret;
3157
0
            }
3158
0
        } else {
3159
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3160
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3161
0
        }
3162
3163
0
        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
0
        ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_hash_from_md_alg(md_alg);
3185
0
        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
0
        if (mbedtls_ssl_own_key(ssl) == NULL) {
3210
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("got no private key"));
3211
0
            return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3212
0
        }
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
0
        if ((ret = mbedtls_pk_sign(mbedtls_ssl_own_key(ssl),
3220
0
                                   md_alg, hash, hashlen,
3221
0
                                   ssl->out_msg + ssl->out_msglen + 2,
3222
0
                                   out_buf_len - ssl->out_msglen - 2,
3223
0
                                   signature_len,
3224
0
                                   ssl->conf->f_rng,
3225
0
                                   ssl->conf->p_rng)) != 0) {
3226
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_sign", ret);
3227
0
            return ret;
3228
0
        }
3229
0
    }
3230
0
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3231
3232
0
    return 0;
3233
0
}
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. */
3239
MBEDTLS_CHECK_RETURN_CRITICAL
3240
static int ssl_write_server_key_exchange(mbedtls_ssl_context *ssl)
3241
0
{
3242
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3243
0
    size_t signature_len = 0;
3244
0
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3245
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3246
0
        ssl->handshake->ciphersuite_info;
3247
0
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3248
3249
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server key exchange"));
3250
3251
0
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3252
    /* Extract static ECDH parameters and abort if ServerKeyExchange
3253
     * is not needed. */
3254
0
    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
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write server key exchange"));
3270
0
        ssl->state++;
3271
0
        return 0;
3272
0
    }
3273
0
#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
0
    {
3286
        /* ServerKeyExchange is needed. Prepare the message. */
3287
0
        ret = ssl_prepare_server_key_exchange(ssl, &signature_len);
3288
0
    }
3289
3290
0
    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
0
        if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3296
0
            MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange (pending)"));
3297
0
        } else {
3298
0
            ssl->out_msglen = 0;
3299
0
        }
3300
0
        return ret;
3301
0
    }
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
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3307
0
    if (signature_len != 0) {
3308
0
        ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_1(signature_len);
3309
0
        ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_0(signature_len);
3310
3311
0
        MBEDTLS_SSL_DEBUG_BUF(3, "my signature",
3312
0
                              ssl->out_msg + ssl->out_msglen,
3313
0
                              signature_len);
3314
3315
        /* Skip over the already-written signature */
3316
0
        ssl->out_msglen += signature_len;
3317
0
    }
3318
0
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3319
3320
    /* Add header and send. */
3321
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3322
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
3323
3324
0
    ssl->state++;
3325
3326
0
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3327
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3328
0
        return ret;
3329
0
    }
3330
3331
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange"));
3332
0
    return 0;
3333
0
}
3334
3335
MBEDTLS_CHECK_RETURN_CRITICAL
3336
static int ssl_write_server_hello_done(mbedtls_ssl_context *ssl)
3337
0
{
3338
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3339
3340
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello done"));
3341
3342
0
    ssl->out_msglen  = 4;
3343
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3344
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
3345
3346
0
    ssl->state++;
3347
3348
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3349
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3350
0
        mbedtls_ssl_send_flight_completed(ssl);
3351
0
    }
3352
0
#endif
3353
3354
0
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3355
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3356
0
        return ret;
3357
0
    }
3358
3359
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3360
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3361
0
        (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
3362
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
3363
0
        return ret;
3364
0
    }
3365
0
#endif /* MBEDTLS_SSL_PROTO_DTLS */
3366
3367
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello done"));
3368
3369
0
    return 0;
3370
0
}
3371
3372
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
3373
    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3374
MBEDTLS_CHECK_RETURN_CRITICAL
3375
static 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)
3415
MBEDTLS_CHECK_RETURN_CRITICAL
3416
static 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
3432
MBEDTLS_CHECK_RETURN_CRITICAL
3433
static 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
3518
MBEDTLS_CHECK_RETURN_CRITICAL
3519
static 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)
3602
MBEDTLS_CHECK_RETURN_CRITICAL
3603
static int ssl_parse_client_psk_identity(mbedtls_ssl_context *ssl, unsigned char **p,
3604
                                         const unsigned char *end)
3605
0
{
3606
0
    int ret = 0;
3607
0
    uint16_t n;
3608
3609
0
    if (ssl_conf_has_psk_or_cb(ssl->conf) == 0) {
3610
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no pre-shared key"));
3611
0
        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3612
0
    }
3613
3614
    /*
3615
     * Receive client pre-shared key identity name
3616
     */
3617
0
    if (end - *p < 2) {
3618
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3619
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3620
0
    }
3621
3622
0
    n = MBEDTLS_GET_UINT16_BE(*p, 0);
3623
0
    *p += 2;
3624
3625
0
    if (n == 0 || n > end - *p) {
3626
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3627
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3628
0
    }
3629
3630
0
    if (ssl->conf->f_psk != NULL) {
3631
0
        if (ssl->conf->f_psk(ssl->conf->p_psk, ssl, *p, n) != 0) {
3632
0
            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3633
0
        }
3634
0
    } 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
0
        if (n != ssl->conf->psk_identity_len ||
3638
0
            mbedtls_ct_memcmp(ssl->conf->psk_identity, *p, n) != 0) {
3639
0
            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3640
0
        }
3641
0
    }
3642
3643
0
    if (ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
3644
0
        MBEDTLS_SSL_DEBUG_BUF(3, "Unknown PSK identity", *p, n);
3645
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3646
0
                                       MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY);
3647
0
        return MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3648
0
    }
3649
3650
0
    *p += n;
3651
3652
0
    return 0;
3653
0
}
3654
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
3655
3656
MBEDTLS_CHECK_RETURN_CRITICAL
3657
static int ssl_parse_client_key_exchange(mbedtls_ssl_context *ssl)
3658
0
{
3659
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3660
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3661
0
    unsigned char *p, *end;
3662
3663
0
    ciphersuite_info = ssl->handshake->ciphersuite_info;
3664
3665
0
    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
0
    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3680
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3681
0
        return ret;
3682
0
    }
3683
3684
0
    p = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
3685
0
    end = ssl->in_msg + ssl->in_hslen;
3686
3687
0
    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
3688
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3689
0
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3690
0
    }
3691
3692
0
    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE) {
3693
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3694
0
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3695
0
    }
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
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
3722
0
    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
3723
0
    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
3724
0
    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
3725
0
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3726
0
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
3727
0
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
3728
0
        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
0
        if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
3792
0
                                            p, (size_t) (end - p))) != 0) {
3793
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
3794
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3795
0
        }
3796
3797
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3798
0
                               MBEDTLS_DEBUG_ECDH_QP);
3799
3800
0
        if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx,
3801
0
                                            &ssl->handshake->pmslen,
3802
0
                                            ssl->handshake->premaster,
3803
0
                                            MBEDTLS_MPI_MAX_SIZE,
3804
0
                                            ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3805
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
3806
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3807
0
        }
3808
3809
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3810
0
                               MBEDTLS_DEBUG_ECDH_Z);
3811
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3812
0
    } else
3813
0
#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
0
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
3818
0
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK) {
3819
0
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3820
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3821
0
            return ret;
3822
0
        }
3823
3824
0
        if (p != end) {
3825
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3826
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3827
0
        }
3828
3829
0
#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3830
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3831
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3832
0
                                                    key_exchange)) != 0) {
3833
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3834
0
            return ret;
3835
0
        }
3836
0
#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3837
0
    } else
3838
0
#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
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4031
0
    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
0
        ret = mbedtls_ecjpake_read_round_two(&ssl->handshake->ecjpake_ctx,
4044
0
                                             p, (size_t) (end - p));
4045
0
        if (ret != 0) {
4046
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_two", ret);
4047
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4048
0
        }
4049
4050
0
        ret = mbedtls_ecjpake_derive_secret(&ssl->handshake->ecjpake_ctx,
4051
0
                                            ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
4052
0
                                            ssl->conf->f_rng, ssl->conf->p_rng);
4053
0
        if (ret != 0) {
4054
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_derive_secret", ret);
4055
0
            return ret;
4056
0
        }
4057
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4058
0
    } else
4059
0
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4060
0
    {
4061
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4062
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4063
0
    }
4064
4065
0
    if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
4066
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
4067
0
        return ret;
4068
0
    }
4069
4070
0
    ssl->state++;
4071
4072
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client key exchange"));
4073
4074
0
    return 0;
4075
0
}
4076
4077
#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
4078
MBEDTLS_CHECK_RETURN_CRITICAL
4079
static 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 */
4096
MBEDTLS_CHECK_RETURN_CRITICAL
4097
static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl)
4098
0
{
4099
0
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4100
0
    size_t i, sig_len;
4101
0
    unsigned char hash[48];
4102
0
    unsigned char *hash_start = hash;
4103
0
    size_t hashlen;
4104
0
    mbedtls_pk_type_t pk_alg;
4105
0
    mbedtls_md_type_t md_alg;
4106
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4107
0
        ssl->handshake->ciphersuite_info;
4108
0
    mbedtls_pk_context *peer_pk;
4109
4110
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate verify"));
4111
4112
0
    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
4113
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4114
0
        ssl->state++;
4115
0
        return 0;
4116
0
    }
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
0
    if (ssl->session_negotiate->peer_cert_digest == NULL) {
4126
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4127
0
        ssl->state++;
4128
0
        return 0;
4129
0
    }
4130
0
#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4131
4132
    /* Read the message without adding it to the checksum */
4133
0
    ret = mbedtls_ssl_read_record(ssl, 0 /* no checksum update */);
4134
0
    if (0 != ret) {
4135
0
        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_read_record"), ret);
4136
0
        return ret;
4137
0
    }
4138
4139
0
    ssl->state++;
4140
4141
    /* Process the message contents */
4142
0
    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
4143
0
        ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY) {
4144
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4145
0
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
4146
0
    }
4147
4148
0
    i = mbedtls_ssl_hs_hdr_len(ssl);
4149
4150
0
#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4151
0
    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
0
    if (i + 2 > ssl->in_hslen) {
4167
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4168
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4169
0
    }
4170
4171
    /*
4172
     * Hash
4173
     */
4174
0
    md_alg = mbedtls_ssl_md_alg_from_hash(ssl->in_msg[i]);
4175
4176
0
    if (md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md(ssl, ssl->in_msg[i])) {
4177
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4178
0
                                  " for verify message"));
4179
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4180
0
    }
4181
4182
0
#if !defined(MBEDTLS_MD_SHA1)
4183
0
    if (MBEDTLS_MD_SHA1 == md_alg) {
4184
0
        hash_start += 16;
4185
0
    }
4186
0
#endif
4187
4188
    /* Info from md_alg will be used instead */
4189
0
    hashlen = 0;
4190
4191
0
    i++;
4192
4193
    /*
4194
     * Signature
4195
     */
4196
0
    if ((pk_alg = mbedtls_ssl_pk_alg_from_sig(ssl->in_msg[i]))
4197
0
        == MBEDTLS_PK_NONE) {
4198
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4199
0
                                  " for verify message"));
4200
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4201
0
    }
4202
4203
    /*
4204
     * Check the certificate's key type matches the signature alg
4205
     */
4206
0
    if (!mbedtls_pk_can_do(peer_pk, pk_alg)) {
4207
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("sig_alg doesn't match cert key"));
4208
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4209
0
    }
4210
4211
0
    i++;
4212
4213
0
    if (i + 2 > ssl->in_hslen) {
4214
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4215
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4216
0
    }
4217
4218
0
    sig_len = MBEDTLS_GET_UINT16_BE(ssl->in_msg, i);
4219
0
    i += 2;
4220
4221
0
    if (i + sig_len != ssl->in_hslen) {
4222
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4223
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4224
0
    }
4225
4226
    /* Calculate hash and verify signature */
4227
0
    {
4228
0
        size_t dummy_hlen;
4229
0
        ret = ssl->handshake->calc_verify(ssl, hash, &dummy_hlen);
4230
0
        if (0 != ret) {
4231
0
            MBEDTLS_SSL_DEBUG_RET(1, ("calc_verify"), ret);
4232
0
            return ret;
4233
0
        }
4234
0
    }
4235
4236
0
    if ((ret = mbedtls_pk_verify(peer_pk,
4237
0
                                 md_alg, hash_start, hashlen,
4238
0
                                 ssl->in_msg + i, sig_len)) != 0) {
4239
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify", ret);
4240
0
        return ret;
4241
0
    }
4242
4243
0
    ret = mbedtls_ssl_update_handshake_status(ssl);
4244
0
    if (0 != ret) {
4245
0
        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_update_handshake_status"), ret);
4246
0
        return ret;
4247
0
    }
4248
4249
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate verify"));
4250
4251
0
    return ret;
4252
0
}
4253
#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4254
4255
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
4256
MBEDTLS_CHECK_RETURN_CRITICAL
4257
static 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
 */
4315
int mbedtls_ssl_handshake_server_step(mbedtls_ssl_context *ssl)
4316
15.0k
{
4317
15.0k
    int ret = 0;
4318
4319
15.0k
    MBEDTLS_SSL_DEBUG_MSG(2, ("server state: %d", ssl->state));
4320
4321
15.0k
    switch (ssl->state) {
4322
4.89k
        case MBEDTLS_SSL_HELLO_REQUEST:
4323
4.89k
            ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
4324
4.89k
            break;
4325
4326
        /*
4327
         *  <==   ClientHello
4328
         */
4329
10.1k
        case MBEDTLS_SSL_CLIENT_HELLO:
4330
10.1k
            ret = ssl_parse_client_hello(ssl);
4331
10.1k
            break;
4332
4333
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
4334
0
        case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
4335
0
            return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED;
4336
0
#endif
4337
4338
        /*
4339
         *  ==>   ServerHello
4340
         *        Certificate
4341
         *      ( ServerKeyExchange  )
4342
         *      ( CertificateRequest )
4343
         *        ServerHelloDone
4344
         */
4345
0
        case MBEDTLS_SSL_SERVER_HELLO:
4346
0
            ret = ssl_write_server_hello(ssl);
4347
0
            break;
4348
4349
0
        case MBEDTLS_SSL_SERVER_CERTIFICATE:
4350
0
            ret = mbedtls_ssl_write_certificate(ssl);
4351
0
            break;
4352
4353
0
        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
4354
0
            ret = ssl_write_server_key_exchange(ssl);
4355
0
            break;
4356
4357
0
        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
4358
0
            ret = ssl_write_certificate_request(ssl);
4359
0
            break;
4360
4361
0
        case MBEDTLS_SSL_SERVER_HELLO_DONE:
4362
0
            ret = ssl_write_server_hello_done(ssl);
4363
0
            break;
4364
4365
        /*
4366
         *  <== ( Certificate/Alert  )
4367
         *        ClientKeyExchange
4368
         *      ( CertificateVerify  )
4369
         *        ChangeCipherSpec
4370
         *        Finished
4371
         */
4372
0
        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
4373
0
            ret = mbedtls_ssl_parse_certificate(ssl);
4374
0
            break;
4375
4376
0
        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
4377
0
            ret = ssl_parse_client_key_exchange(ssl);
4378
0
            break;
4379
4380
0
        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
4381
0
            ret = ssl_parse_certificate_verify(ssl);
4382
0
            break;
4383
4384
0
        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
4385
0
            ret = mbedtls_ssl_parse_change_cipher_spec(ssl);
4386
0
            break;
4387
4388
0
        case MBEDTLS_SSL_CLIENT_FINISHED:
4389
0
            ret = mbedtls_ssl_parse_finished(ssl);
4390
0
            break;
4391
4392
        /*
4393
         *  ==> ( NewSessionTicket )
4394
         *        ChangeCipherSpec
4395
         *        Finished
4396
         */
4397
0
        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
0
            ret = mbedtls_ssl_write_change_cipher_spec(ssl);
4404
0
            break;
4405
4406
0
        case MBEDTLS_SSL_SERVER_FINISHED:
4407
0
            ret = mbedtls_ssl_write_finished(ssl);
4408
0
            break;
4409
4410
0
        case MBEDTLS_SSL_FLUSH_BUFFERS:
4411
0
            MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
4412
0
            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
4413
0
            break;
4414
4415
0
        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
4416
0
            mbedtls_ssl_handshake_wrapup(ssl);
4417
0
            break;
4418
4419
0
        default:
4420
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
4421
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4422
15.0k
    }
4423
4424
15.0k
    return ret;
4425
15.0k
}
4426
4427
void mbedtls_ssl_conf_preference_order(mbedtls_ssl_config *conf, int order)
4428
0
{
4429
0
    conf->respect_cli_pref = order;
4430
0
}
4431
4432
#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_PROTO_TLS1_2 */