Coverage Report

Created: 2024-06-20 06:04

/src/mbedtls/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
0
{
31
0
    return psa_status_to_mbedtls(status, psa_to_ssl_errors,
32
0
                                 ARRAY_LENGTH(psa_to_ssl_errors),
33
0
                                 psa_generic_status_to_mbedtls);
34
0
}
35
0
#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
1.11k
{
52
1.11k
    if (ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER) {
53
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
54
0
    }
55
56
1.11k
    mbedtls_free(ssl->cli_id);
57
58
1.11k
    if ((ssl->cli_id = mbedtls_calloc(1, ilen)) == NULL) {
59
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
60
0
    }
61
62
1.11k
    memcpy(ssl->cli_id, info, ilen);
63
1.11k
    ssl->cli_id_len = ilen;
64
65
1.11k
    return 0;
66
1.11k
}
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
1.11k
{
73
1.11k
    conf->f_cookie_write = f_cookie_write;
74
1.11k
    conf->f_cookie_check = f_cookie_check;
75
1.11k
    conf->p_cookie       = p_cookie;
76
1.11k
}
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
2.09k
{
83
2.09k
    if (conf->f_psk != NULL) {
84
0
        return 1;
85
0
    }
86
87
2.09k
    if (conf->psk_identity_len == 0 || conf->psk_identity == NULL) {
88
1.41k
        return 0;
89
1.41k
    }
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
673
    if (conf->psk != NULL && conf->psk_len != 0) {
99
673
        return 1;
100
673
    }
101
102
0
    return 0;
103
673
}
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
392
{
111
392
#if defined(MBEDTLS_SSL_RENEGOTIATION)
112
392
    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
113
        /* Check verify-data in constant-time. The length OTOH is no secret */
114
0
        if (len    != 1 + ssl->verify_data_len ||
115
0
            buf[0] !=     ssl->verify_data_len ||
116
0
            mbedtls_ct_memcmp(buf + 1, ssl->peer_verify_data,
117
0
                              ssl->verify_data_len) != 0) {
118
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("non-matching renegotiation info"));
119
0
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
120
0
                                           MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
121
0
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
122
0
        }
123
0
    } else
124
392
#endif /* MBEDTLS_SSL_RENEGOTIATION */
125
392
    {
126
392
        if (len != 1 || buf[0] != 0x0) {
127
33
            MBEDTLS_SSL_DEBUG_MSG(1, ("non-zero length renegotiation info"));
128
33
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
129
33
                                           MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
130
33
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
131
33
        }
132
133
359
        ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
134
359
    }
135
136
359
    return 0;
137
392
}
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
227
{
185
227
    size_t list_size, our_size;
186
227
    const unsigned char *p;
187
227
    uint16_t *curves_tls_id;
188
189
227
    if (len < 2) {
190
3
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
191
3
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
192
3
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
193
3
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
194
3
    }
195
224
    list_size = MBEDTLS_GET_UINT16_BE(buf, 0);
196
224
    if (list_size + 2 != len ||
197
224
        list_size % 2 != 0) {
198
64
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
199
64
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
200
64
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
201
64
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
202
64
    }
203
204
    /* Should never happen unless client duplicates the extension */
205
160
    if (ssl->handshake->curves_tls_id != NULL) {
206
2
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
207
2
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
208
2
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
209
2
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
210
2
    }
211
212
    /* Don't allow our peer to make us allocate too much memory,
213
     * and leave room for a final 0 */
214
158
    our_size = list_size / 2 + 1;
215
158
    if (our_size > MBEDTLS_ECP_DP_MAX) {
216
36
        our_size = MBEDTLS_ECP_DP_MAX;
217
36
    }
218
219
158
    if ((curves_tls_id = mbedtls_calloc(our_size,
220
158
                                        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
158
    ssl->handshake->curves_tls_id = curves_tls_id;
227
228
158
    p = buf + 2;
229
2.87k
    while (list_size > 0 && our_size > 1) {
230
2.71k
        uint16_t curr_tls_id = MBEDTLS_GET_UINT16_BE(p, 0);
231
232
2.71k
        if (mbedtls_ssl_get_ecp_group_id_from_tls_id(curr_tls_id) !=
233
2.71k
            MBEDTLS_ECP_DP_NONE) {
234
380
            *curves_tls_id++ = curr_tls_id;
235
380
            our_size--;
236
380
        }
237
238
2.71k
        list_size -= 2;
239
2.71k
        p += 2;
240
2.71k
    }
241
242
158
    return 0;
243
158
}
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
3.15k
{
250
3.15k
    size_t list_size;
251
3.15k
    const unsigned char *p;
252
253
3.15k
    if (len == 0 || (size_t) (buf[0] + 1) != len) {
254
47
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
255
47
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
256
47
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
257
47
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
258
47
    }
259
3.11k
    list_size = buf[0];
260
261
3.11k
    p = buf + 1;
262
6.88k
    while (list_size > 0) {
263
5.16k
        if (p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED ||
264
5.16k
            p[0] == MBEDTLS_ECP_PF_COMPRESSED) {
265
1.39k
#if !defined(MBEDTLS_USE_PSA_CRYPTO) && \
266
1.39k
            defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED)
267
1.39k
            ssl->handshake->ecdh_ctx.point_format = p[0];
268
1.39k
#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED */
269
1.39k
#if !defined(MBEDTLS_USE_PSA_CRYPTO) &&                             \
270
1.39k
            defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
271
1.39k
            mbedtls_ecjpake_set_point_format(&ssl->handshake->ecjpake_ctx,
272
1.39k
                                             p[0]);
273
1.39k
#endif /* !MBEDTLS_USE_PSA_CRYPTO && MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
274
1.39k
            MBEDTLS_SSL_DEBUG_MSG(4, ("point format selected: %d", p[0]));
275
1.39k
            return 0;
276
1.39k
        }
277
278
3.77k
        list_size--;
279
3.77k
        p++;
280
3.77k
    }
281
282
1.71k
    return 0;
283
3.11k
}
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
537
{
294
537
    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
537
    if (mbedtls_ecjpake_check(&ssl->handshake->ecjpake_ctx) != 0)
300
537
#endif /* MBEDTLS_USE_PSA_CRYPTO */
301
537
    {
302
537
        MBEDTLS_SSL_DEBUG_MSG(3, ("skip ecjpake kkpp extension"));
303
537
        return 0;
304
537
    }
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
618
{
344
618
    if (len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID) {
345
22
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
346
22
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
347
22
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
348
22
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
349
22
    }
350
351
596
    ssl->session_negotiate->mfl_code = buf[0];
352
353
596
    return 0;
354
618
}
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
339
{
363
339
    size_t peer_cid_len;
364
365
    /* CID extension only makes sense in DTLS */
366
339
    if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
367
2
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
368
2
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
369
2
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
370
2
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
371
2
    }
372
373
    /*
374
     *   struct {
375
     *      opaque cid<0..2^8-1>;
376
     *   } ConnectionId;
377
     */
378
379
337
    if (len < 1) {
380
2
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
381
2
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
382
2
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
383
2
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
384
2
    }
385
386
335
    peer_cid_len = *buf++;
387
335
    len--;
388
389
335
    if (len != peer_cid_len) {
390
13
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
391
13
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
392
13
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
393
13
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
394
13
    }
395
396
    /* Ignore CID if the user has disabled its use. */
397
322
    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
322
        MBEDTLS_SSL_DEBUG_MSG(3, ("Client sent CID extension, but CID disabled"));
401
322
        return 0;
402
322
    }
403
404
0
    if (peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX) {
405
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
406
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
407
0
                                       MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER);
408
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
409
0
    }
410
411
0
    ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED;
412
0
    ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len;
413
0
    memcpy(ssl->handshake->peer_cid, buf, peer_cid_len);
414
415
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("Use of CID extension negotiated"));
416
0
    MBEDTLS_SSL_DEBUG_BUF(3, "Client CID", buf, peer_cid_len);
417
418
0
    return 0;
419
0
}
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
918
{
428
918
    if (len != 0) {
429
17
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
430
17
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
431
17
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
432
17
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
433
17
    }
434
435
901
    ((void) buf);
436
437
901
    if (ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED) {
438
627
        ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
439
627
    }
440
441
901
    return 0;
442
918
}
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
1.43k
{
451
1.43k
    if (len != 0) {
452
26
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
453
26
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
454
26
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
455
26
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
456
26
    }
457
458
1.40k
    ((void) buf);
459
460
1.40k
    if (ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED) {
461
1.04k
        ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
462
1.04k
    }
463
464
1.40k
    return 0;
465
1.43k
}
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
2.87k
{
474
2.87k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
475
2.87k
    mbedtls_ssl_session session;
476
477
2.87k
    mbedtls_ssl_session_init(&session);
478
479
2.87k
    if (ssl->conf->f_ticket_parse == NULL ||
480
2.87k
        ssl->conf->f_ticket_write == NULL) {
481
739
        return 0;
482
739
    }
483
484
    /* Remember the client asked us to send a new ticket */
485
2.13k
    ssl->handshake->new_session_ticket = 1;
486
487
2.13k
    MBEDTLS_SSL_DEBUG_MSG(3, ("ticket length: %" MBEDTLS_PRINTF_SIZET, len));
488
489
2.13k
    if (len == 0) {
490
210
        return 0;
491
210
    }
492
493
1.92k
#if defined(MBEDTLS_SSL_RENEGOTIATION)
494
1.92k
    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
495
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("ticket rejected: renegotiating"));
496
0
        return 0;
497
0
    }
498
1.92k
#endif /* MBEDTLS_SSL_RENEGOTIATION */
499
500
    /*
501
     * Failures are ok: just ignore the ticket and proceed.
502
     */
503
1.92k
    if ((ret = ssl->conf->f_ticket_parse(ssl->conf->p_ticket, &session,
504
1.92k
                                         buf, len)) != 0) {
505
1.92k
        mbedtls_ssl_session_free(&session);
506
507
1.92k
        if (ret == MBEDTLS_ERR_SSL_INVALID_MAC) {
508
690
            MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is not authentic"));
509
1.23k
        } else if (ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED) {
510
223
            MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is expired"));
511
1.01k
        } else {
512
1.01k
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_ticket_parse", ret);
513
1.01k
        }
514
515
1.92k
        return 0;
516
1.92k
    }
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
0
    session.id_len = ssl->session_negotiate->id_len;
523
0
    memcpy(&session.id, ssl->session_negotiate->id, session.id_len);
524
525
0
    mbedtls_ssl_session_free(ssl->session_negotiate);
526
0
    memcpy(ssl->session_negotiate, &session, sizeof(mbedtls_ssl_session));
527
528
    /* Zeroize instead of free as we copied the content */
529
0
    mbedtls_platform_zeroize(&session, sizeof(mbedtls_ssl_session));
530
531
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("session successfully restored from ticket"));
532
533
0
    ssl->handshake->resume = 1;
534
535
    /* Don't send a new ticket after all, this one is OK */
536
0
    ssl->handshake->new_session_ticket = 0;
537
538
0
    return 0;
539
1.92k
}
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
186
{
548
186
    mbedtls_ssl_srtp_profile client_protection = MBEDTLS_TLS_SRTP_UNSET;
549
186
    size_t i, j;
550
186
    size_t profile_length;
551
186
    uint16_t mki_length;
552
    /*! 2 bytes for profile length and 1 byte for mki len */
553
186
    const size_t size_of_lengths = 3;
554
555
    /* If use_srtp is not configured, just ignore the extension */
556
186
    if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
557
186
        (ssl->conf->dtls_srtp_profile_list == NULL) ||
558
186
        (ssl->conf->dtls_srtp_profile_list_len == 0)) {
559
186
        return 0;
560
186
    }
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
0
    if (len < size_of_lengths) {
580
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
581
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
582
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
583
0
    }
584
585
0
    ssl->dtls_srtp_info.chosen_dtls_srtp_profile = MBEDTLS_TLS_SRTP_UNSET;
586
587
    /* first 2 bytes are protection profile length(in bytes) */
588
0
    profile_length = (buf[0] << 8) | buf[1];
589
0
    buf += 2;
590
591
    /* The profile length cannot be bigger than input buffer size - lengths fields */
592
0
    if (profile_length > len - size_of_lengths ||
593
0
        profile_length % 2 != 0) { /* profiles are 2 bytes long, so the length must be even */
594
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
595
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
596
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
597
0
    }
598
    /*
599
     * parse the extension list values are defined in
600
     * http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
601
     */
602
0
    for (j = 0; j < profile_length; j += 2) {
603
0
        uint16_t protection_profile_value = buf[j] << 8 | buf[j + 1];
604
0
        client_protection = mbedtls_ssl_check_srtp_profile_value(protection_profile_value);
605
606
0
        if (client_protection != MBEDTLS_TLS_SRTP_UNSET) {
607
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("found srtp profile: %s",
608
0
                                      mbedtls_ssl_get_srtp_profile_as_string(
609
0
                                          client_protection)));
610
0
        } else {
611
0
            continue;
612
0
        }
613
        /* check if suggested profile is in our list */
614
0
        for (i = 0; i < ssl->conf->dtls_srtp_profile_list_len; i++) {
615
0
            if (client_protection == ssl->conf->dtls_srtp_profile_list[i]) {
616
0
                ssl->dtls_srtp_info.chosen_dtls_srtp_profile = ssl->conf->dtls_srtp_profile_list[i];
617
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("selected srtp profile: %s",
618
0
                                          mbedtls_ssl_get_srtp_profile_as_string(
619
0
                                              client_protection)));
620
0
                break;
621
0
            }
622
0
        }
623
0
        if (ssl->dtls_srtp_info.chosen_dtls_srtp_profile != MBEDTLS_TLS_SRTP_UNSET) {
624
0
            break;
625
0
        }
626
0
    }
627
0
    buf += profile_length; /* buf points to the mki length */
628
0
    mki_length = *buf;
629
0
    buf++;
630
631
0
    if (mki_length > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH ||
632
0
        mki_length + profile_length + size_of_lengths != len) {
633
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
634
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
635
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
636
0
    }
637
638
    /* Parse the mki only if present and mki is supported locally */
639
0
    if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED &&
640
0
        mki_length > 0) {
641
0
        ssl->dtls_srtp_info.mki_len = mki_length;
642
643
0
        memcpy(ssl->dtls_srtp_info.mki_value, buf, mki_length);
644
645
0
        MBEDTLS_SSL_DEBUG_BUF(3, "using mki",  ssl->dtls_srtp_info.mki_value,
646
0
                              ssl->dtls_srtp_info.mki_len);
647
0
    }
648
649
0
    return 0;
650
0
}
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
2.63k
{
690
2.63k
    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
2.63k
    mbedtls_pk_type_t pk_alg =
698
2.63k
        mbedtls_ssl_get_ciphersuite_sig_pk_alg(ciphersuite_info);
699
2.63k
#endif /* MBEDTLS_USE_PSA_CRYPTO */
700
2.63k
    uint32_t flags;
701
702
2.63k
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
703
2.63k
    if (ssl->handshake->sni_key_cert != NULL) {
704
0
        list = ssl->handshake->sni_key_cert;
705
0
    } else
706
2.63k
#endif
707
2.63k
    list = ssl->conf->key_cert;
708
709
2.63k
    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
2.63k
    pk_alg_is_none = (pk_alg == MBEDTLS_PK_NONE);
714
2.63k
#endif /* MBEDTLS_USE_PSA_CRYPTO */
715
2.63k
    if (pk_alg_is_none) {
716
202
        return 0;
717
202
    }
718
719
2.43k
    MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite requires certificate"));
720
721
2.43k
    if (list == NULL) {
722
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("server has no certificate"));
723
0
        return -1;
724
0
    }
725
726
4.87k
    for (cur = list; cur != NULL; cur = cur->next) {
727
2.43k
        flags = 0;
728
2.43k
        MBEDTLS_SSL_DEBUG_CRT(3, "candidate certificate chain, certificate",
729
2.43k
                              cur->cert);
730
731
2.43k
        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
2.43k
        key_type_matches = mbedtls_pk_can_do(&cur->cert->pk, pk_alg);
744
2.43k
#endif /* MBEDTLS_USE_PSA_CRYPTO */
745
2.43k
        if (!key_type_matches) {
746
2.43k
            MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: key type"));
747
2.43k
            continue;
748
2.43k
        }
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
2.43k
    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
2.43k
    return -1;
787
2.43k
}
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
6.94k
{
798
6.94k
    const mbedtls_ssl_ciphersuite_t *suite_info;
799
800
6.94k
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
801
6.94k
    mbedtls_pk_type_t sig_type;
802
6.94k
#endif
803
804
6.94k
    suite_info = mbedtls_ssl_ciphersuite_from_id(suite_id);
805
6.94k
    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
6.94k
    MBEDTLS_SSL_DEBUG_MSG(3, ("trying ciphersuite: %#04x (%s)",
811
6.94k
                              (unsigned int) suite_id, suite_info->name));
812
813
6.94k
    if (suite_info->min_tls_version > ssl->tls_version ||
814
6.94k
        suite_info->max_tls_version < ssl->tls_version) {
815
449
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: version"));
816
449
        return 0;
817
449
    }
818
819
6.50k
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
820
6.50k
    if (suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE &&
821
6.50k
        (ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK) == 0) {
822
457
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: ecjpake "
823
457
                                  "not configured or ext missing"));
824
457
        return 0;
825
457
    }
826
6.04k
#endif
827
828
829
6.04k
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
830
6.04k
    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
831
6.04k
    if (mbedtls_ssl_ciphersuite_uses_ec(suite_info) &&
832
6.04k
        (ssl->handshake->curves_tls_id == NULL ||
833
2.44k
         ssl->handshake->curves_tls_id[0] == 0)) {
834
1.98k
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: "
835
1.98k
                                  "no common elliptic curve"));
836
1.98k
        return 0;
837
1.98k
    }
838
4.05k
#endif
839
840
4.05k
#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
4.05k
    if (mbedtls_ssl_ciphersuite_uses_psk(suite_info) &&
844
4.05k
        ssl_conf_has_psk_or_cb(ssl->conf) == 0) {
845
1.41k
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: no pre-shared key"));
846
1.41k
        return 0;
847
1.41k
    }
848
2.63k
#endif
849
850
2.63k
#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
2.63k
    if (ssl_pick_cert(ssl, suite_info) != 0) {
859
2.43k
        MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite mismatch: "
860
2.43k
                                  "no suitable certificate"));
861
2.43k
        return 0;
862
2.43k
    }
863
202
#endif
864
865
202
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
866
    /* If the ciphersuite requires signing, check whether
867
     * a suitable hash algorithm is present. */
868
202
    sig_type = mbedtls_ssl_get_ciphersuite_sig_alg(suite_info);
869
202
    if (sig_type != MBEDTLS_PK_NONE &&
870
202
        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
202
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
878
879
202
    *ciphersuite_info = suite_info;
880
202
    return 0;
881
202
}
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
1.98k
{
889
1.98k
    int ret, got_common_suite;
890
1.98k
    size_t i, j;
891
1.98k
    size_t ciph_offset, comp_offset, ext_offset;
892
1.98k
    size_t msg_len, ciph_len, sess_len, comp_len, ext_len;
893
1.98k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
894
1.98k
    size_t cookie_offset, cookie_len;
895
1.98k
#endif
896
1.98k
    unsigned char *buf, *p, *ext;
897
1.98k
#if defined(MBEDTLS_SSL_RENEGOTIATION)
898
1.98k
    int renegotiation_info_seen = 0;
899
1.98k
#endif
900
1.98k
    int handshake_failure = 0;
901
1.98k
    const int *ciphersuites;
902
1.98k
    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
1.98k
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
908
1.98k
    int sig_hash_alg_ext_present = 0;
909
1.98k
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
910
911
1.98k
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client hello"));
912
913
1.98k
    int renegotiating;
914
915
1.98k
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
916
1.98k
read_record_header:
917
1.98k
#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
1.98k
    renegotiating = 0;
927
1.98k
#if defined(MBEDTLS_SSL_RENEGOTIATION)
928
1.98k
    renegotiating = (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE);
929
1.98k
#endif
930
1.98k
    if (!renegotiating && !ssl->keep_current_message) {
931
1.11k
        if ((ret = mbedtls_ssl_fetch_input(ssl, 5)) != 0) {
932
            /* No alert on a read error. */
933
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
934
0
            return ret;
935
0
        }
936
1.11k
    }
937
938
1.98k
    buf = ssl->in_hdr;
939
940
1.98k
    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
1.98k
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, message type: %d",
952
1.98k
                              buf[0]));
953
954
1.98k
    if (buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE) {
955
8
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
956
8
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
957
8
    }
958
959
1.98k
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, message len.: %d",
960
1.98k
                              MBEDTLS_GET_UINT16_BE(ssl->in_len, 0)));
961
962
1.98k
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello, protocol version: [%d:%d]",
963
1.98k
                              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
1.98k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
968
1.98k
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM
969
1.98k
#if defined(MBEDTLS_SSL_RENEGOTIATION)
970
1.98k
        && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
971
1.98k
#endif
972
1.98k
        ) {
973
        /* Epoch should be 0 for initial handshakes */
974
1.10k
        if (ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0) {
975
12
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
976
12
            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
977
12
        }
978
979
1.09k
        memcpy(&ssl->cur_out_ctr[2], ssl->in_ctr + 2,
980
1.09k
               sizeof(ssl->cur_out_ctr) - 2);
981
982
1.09k
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
983
1.09k
        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.09k
        mbedtls_ssl_dtls_replay_update(ssl);
992
1.09k
#endif
993
1.09k
    }
994
1.96k
#endif /* MBEDTLS_SSL_PROTO_DTLS */
995
996
1.96k
    msg_len = MBEDTLS_GET_UINT16_BE(ssl->in_len, 0);
997
998
1.96k
#if defined(MBEDTLS_SSL_RENEGOTIATION)
999
1.96k
    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
1000
        /* Set by mbedtls_ssl_read_record() */
1001
0
        msg_len = ssl->in_hslen;
1002
0
    } else
1003
1.96k
#endif
1004
1.96k
    {
1005
1.96k
        if (ssl->keep_current_message) {
1006
877
            ssl->keep_current_message = 0;
1007
1.09k
        } else {
1008
1.09k
            if (msg_len > MBEDTLS_SSL_IN_CONTENT_LEN) {
1009
5
                MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1010
5
                return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1011
5
            }
1012
1013
1.08k
            if ((ret = mbedtls_ssl_fetch_input(ssl,
1014
1.08k
                                               mbedtls_ssl_in_hdr_len(ssl) + msg_len)) != 0) {
1015
145
                MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_fetch_input", ret);
1016
145
                return ret;
1017
145
            }
1018
1019
            /* Done reading this record, get ready for the next one */
1020
941
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1021
941
            if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1022
941
                ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len(ssl);
1023
941
            } else
1024
0
#endif
1025
0
            ssl->in_left = 0;
1026
941
        }
1027
1.96k
    }
1028
1029
1.81k
    buf = ssl->in_msg;
1030
1031
1.81k
    MBEDTLS_SSL_DEBUG_BUF(4, "record contents", buf, msg_len);
1032
1033
1.81k
    ret = ssl->handshake->update_checksum(ssl, buf, msg_len);
1034
1.81k
    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
1.81k
    if (msg_len < mbedtls_ssl_hs_hdr_len(ssl)) {
1048
20
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1049
20
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1050
20
    }
1051
1052
1.79k
    MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, handshake type: %d", buf[0]));
1053
1054
1.79k
    if (buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO) {
1055
78
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1056
78
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
1057
78
    }
1058
1.72k
    {
1059
1.72k
        size_t handshake_len = MBEDTLS_GET_UINT24_BE(buf, 1);
1060
1.72k
        MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, handshake len.: %u",
1061
1.72k
                                  (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
1.72k
        if (buf[1] != 0) {
1066
14
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message: %u != 0",
1067
14
                                      (unsigned) buf[1]));
1068
14
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1069
14
        }
1070
1071
        /* We don't support fragmentation of ClientHello (yet?) */
1072
1.70k
        if (msg_len != mbedtls_ssl_hs_hdr_len(ssl) + handshake_len) {
1073
116
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message: %u != %u + %u",
1074
116
                                      (unsigned) msg_len,
1075
116
                                      (unsigned) mbedtls_ssl_hs_hdr_len(ssl),
1076
116
                                      (unsigned) handshake_len));
1077
116
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1078
116
        }
1079
1.70k
    }
1080
1081
1.59k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1082
1.59k
    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
787
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1088
787
        if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
1089
            /* This couldn't be done in ssl_prepare_handshake_record() */
1090
0
            unsigned int cli_msg_seq = (unsigned int) MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
1091
0
            if (cli_msg_seq != ssl->handshake->in_msg_seq) {
1092
0
                MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message_seq: "
1093
0
                                          "%u (expected %u)", cli_msg_seq,
1094
0
                                          ssl->handshake->in_msg_seq));
1095
0
                return MBEDTLS_ERR_SSL_DECODE_ERROR;
1096
0
            }
1097
1098
0
            ssl->handshake->in_msg_seq++;
1099
0
        } else
1100
787
#endif
1101
787
        {
1102
787
            unsigned int cli_msg_seq = (unsigned int) MBEDTLS_GET_UINT16_BE(ssl->in_msg, 4);
1103
787
            ssl->handshake->out_msg_seq = cli_msg_seq;
1104
787
            ssl->handshake->in_msg_seq  = cli_msg_seq + 1;
1105
787
        }
1106
787
        {
1107
            /*
1108
             * For now we don't support fragmentation, so make sure
1109
             * fragment_offset == 0 and fragment_length == length
1110
             */
1111
787
            size_t fragment_offset, fragment_length, length;
1112
787
            fragment_offset = MBEDTLS_GET_UINT24_BE(ssl->in_msg, 6);
1113
787
            fragment_length = MBEDTLS_GET_UINT24_BE(ssl->in_msg, 9);
1114
787
            length = MBEDTLS_GET_UINT24_BE(ssl->in_msg, 1);
1115
787
            MBEDTLS_SSL_DEBUG_MSG(
1116
787
                4, ("fragment_offset=%u fragment_length=%u length=%u",
1117
787
                    (unsigned) fragment_offset, (unsigned) fragment_length,
1118
787
                    (unsigned) length));
1119
787
            if (fragment_offset != 0 || length != fragment_length) {
1120
57
                MBEDTLS_SSL_DEBUG_MSG(1, ("ClientHello fragmentation not supported"));
1121
57
                return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
1122
57
            }
1123
787
        }
1124
787
    }
1125
1.53k
#endif /* MBEDTLS_SSL_PROTO_DTLS */
1126
1127
1.53k
    buf += mbedtls_ssl_hs_hdr_len(ssl);
1128
1.53k
    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
1.53k
    if (msg_len < 38) {
1152
6
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1153
6
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1154
6
    }
1155
1156
    /*
1157
     * Check and save the protocol version
1158
     */
1159
1.52k
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, version", buf, 2);
1160
1161
1.52k
    ssl->tls_version = (mbedtls_ssl_protocol_version) mbedtls_ssl_read_version(buf,
1162
1.52k
                                                                               ssl->conf->transport);
1163
1.52k
    ssl->session_negotiate->tls_version = ssl->tls_version;
1164
1.52k
    ssl->session_negotiate->endpoint = ssl->conf->endpoint;
1165
1166
1.52k
    if (ssl->tls_version != MBEDTLS_SSL_VERSION_TLS1_2) {
1167
37
        MBEDTLS_SSL_DEBUG_MSG(1, ("server only supports TLS 1.2"));
1168
37
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1169
37
                                       MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION);
1170
37
        return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1171
37
    }
1172
1173
    /*
1174
     * Save client random (inc. Unix time)
1175
     */
1176
1.49k
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, random bytes", buf + 2, 32);
1177
1178
1.49k
    memcpy(ssl->handshake->randbytes, buf + 2, 32);
1179
1180
    /*
1181
     * Check the session ID length and save session ID
1182
     */
1183
1.49k
    sess_len = buf[34];
1184
1185
1.49k
    if (sess_len > sizeof(ssl->session_negotiate->id) ||
1186
1.49k
        sess_len + 34 + 2 > msg_len) { /* 2 for cipherlist length field */
1187
13
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1188
13
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1189
13
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1190
13
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1191
13
    }
1192
1193
1.47k
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, session id", buf + 35, sess_len);
1194
1195
1.47k
    ssl->session_negotiate->id_len = sess_len;
1196
1.47k
    memset(ssl->session_negotiate->id, 0,
1197
1.47k
           sizeof(ssl->session_negotiate->id));
1198
1.47k
    memcpy(ssl->session_negotiate->id, buf + 35,
1199
1.47k
           ssl->session_negotiate->id_len);
1200
1201
    /*
1202
     * Check the cookie length and content
1203
     */
1204
1.47k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1205
1.47k
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1206
679
        cookie_offset = 35 + sess_len;
1207
679
        cookie_len = buf[cookie_offset];
1208
1209
679
        if (cookie_offset + 1 + cookie_len + 2 > msg_len) {
1210
11
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1211
11
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1212
11
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1213
11
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1214
11
        }
1215
1216
668
        MBEDTLS_SSL_DEBUG_BUF(3, "client hello, cookie",
1217
668
                              buf + cookie_offset + 1, cookie_len);
1218
1219
668
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
1220
668
        if (ssl->conf->f_cookie_check != NULL
1221
668
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1222
668
            && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE
1223
668
#endif
1224
668
            ) {
1225
668
            if (ssl->conf->f_cookie_check(ssl->conf->p_cookie,
1226
668
                                          buf + cookie_offset + 1, cookie_len,
1227
668
                                          ssl->cli_id, ssl->cli_id_len) != 0) {
1228
668
                MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification failed"));
1229
668
                ssl->handshake->cookie_verify_result = 1;
1230
668
            } else {
1231
0
                MBEDTLS_SSL_DEBUG_MSG(2, ("cookie verification passed"));
1232
0
                ssl->handshake->cookie_verify_result = 0;
1233
0
            }
1234
668
        } 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
668
        ciph_offset = cookie_offset + 1 + cookie_len;
1251
668
    } else
1252
798
#endif /* MBEDTLS_SSL_PROTO_DTLS */
1253
798
    ciph_offset = 35 + sess_len;
1254
1255
1.46k
    ciph_len = MBEDTLS_GET_UINT16_BE(buf, ciph_offset);
1256
1257
1.46k
    if (ciph_len < 2 ||
1258
1.46k
        ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */
1259
1.46k
        (ciph_len % 2) != 0) {
1260
57
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1261
57
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1262
57
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1263
57
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1264
57
    }
1265
1266
1.40k
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, ciphersuitelist",
1267
1.40k
                          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
1.40k
    comp_offset = ciph_offset + 2 + ciph_len;
1276
1277
1.40k
    comp_len = buf[comp_offset];
1278
1279
1.40k
    if (comp_len < 1 ||
1280
1.40k
        comp_len > 16 ||
1281
1.40k
        comp_len + comp_offset + 1 > msg_len) {
1282
36
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1283
36
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1284
36
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1285
36
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1286
36
    }
1287
1288
1.37k
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, compression",
1289
1.37k
                          buf + comp_offset + 1, comp_len);
1290
1291
    /*
1292
     * Check the extension length
1293
     */
1294
1.37k
    ext_offset = comp_offset + 1 + comp_len;
1295
1.37k
    if (msg_len > ext_offset) {
1296
1.24k
        if (msg_len < ext_offset + 2) {
1297
4
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1298
4
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1299
4
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1300
4
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1301
4
        }
1302
1303
1.23k
        ext_len = MBEDTLS_GET_UINT16_BE(buf, ext_offset);
1304
1305
1.23k
        if (msg_len != ext_offset + 2 + ext_len) {
1306
86
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1307
86
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1308
86
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1309
86
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1310
86
        }
1311
1.23k
    } else {
1312
132
        ext_len = 0;
1313
132
    }
1314
1315
1.28k
    ext = buf + ext_offset + 2;
1316
1.28k
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello extensions", ext, ext_len);
1317
1318
23.4k
    while (ext_len != 0) {
1319
23.0k
        unsigned int ext_id;
1320
23.0k
        unsigned int ext_size;
1321
23.0k
        if (ext_len < 4) {
1322
32
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1323
32
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1324
32
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1325
32
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1326
32
        }
1327
22.9k
        ext_id   = MBEDTLS_GET_UINT16_BE(ext, 0);
1328
22.9k
        ext_size = MBEDTLS_GET_UINT16_BE(ext, 2);
1329
1330
22.9k
        if (ext_size + 4 > ext_len) {
1331
178
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1332
178
            mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1333
178
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
1334
178
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
1335
178
        }
1336
22.8k
        switch (ext_id) {
1337
0
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1338
2.01k
            case MBEDTLS_TLS_EXT_SERVERNAME:
1339
2.01k
                MBEDTLS_SSL_DEBUG_MSG(3, ("found ServerName extension"));
1340
2.01k
                ret = mbedtls_ssl_parse_server_name_ext(ssl, ext + 4,
1341
2.01k
                                                        ext + 4 + ext_size);
1342
2.01k
                if (ret != 0) {
1343
118
                    return ret;
1344
118
                }
1345
1.90k
                break;
1346
1.90k
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1347
1348
1.90k
            case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO:
1349
392
                MBEDTLS_SSL_DEBUG_MSG(3, ("found renegotiation extension"));
1350
392
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1351
392
                renegotiation_info_seen = 1;
1352
392
#endif
1353
1354
392
                ret = ssl_parse_renegotiation_info(ssl, ext + 4, ext_size);
1355
392
                if (ret != 0) {
1356
33
                    return ret;
1357
33
                }
1358
359
                break;
1359
1360
359
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1361
830
            case MBEDTLS_TLS_EXT_SIG_ALG:
1362
830
                MBEDTLS_SSL_DEBUG_MSG(3, ("found signature_algorithms extension"));
1363
1364
830
                ret = mbedtls_ssl_parse_sig_alg_ext(ssl, ext + 4, ext + 4 + ext_size);
1365
830
                if (ret != 0) {
1366
210
                    return ret;
1367
210
                }
1368
1369
620
                sig_hash_alg_ext_present = 1;
1370
620
                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
227
            case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
1377
227
                MBEDTLS_SSL_DEBUG_MSG(3, ("found supported elliptic curves extension"));
1378
1379
227
                ret = ssl_parse_supported_groups_ext(ssl, ext + 4, ext_size);
1380
227
                if (ret != 0) {
1381
69
                    return ret;
1382
69
                }
1383
158
                break;
1384
1385
3.15k
            case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS:
1386
3.15k
                MBEDTLS_SSL_DEBUG_MSG(3, ("found supported point formats extension"));
1387
3.15k
                ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT;
1388
1389
3.15k
                ret = ssl_parse_supported_point_formats(ssl, ext + 4, ext_size);
1390
3.15k
                if (ret != 0) {
1391
47
                    return ret;
1392
47
                }
1393
3.11k
                break;
1394
3.11k
#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
3.11k
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
1399
3.11k
            case MBEDTLS_TLS_EXT_ECJPAKE_KKPP:
1400
537
                MBEDTLS_SSL_DEBUG_MSG(3, ("found ecjpake kkpp extension"));
1401
1402
537
                ret = ssl_parse_ecjpake_kkpp(ssl, ext + 4, ext_size);
1403
537
                if (ret != 0) {
1404
0
                    return ret;
1405
0
                }
1406
537
                break;
1407
537
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
1408
1409
537
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
1410
618
            case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH:
1411
618
                MBEDTLS_SSL_DEBUG_MSG(3, ("found max fragment length extension"));
1412
1413
618
                ret = ssl_parse_max_fragment_length_ext(ssl, ext + 4, ext_size);
1414
618
                if (ret != 0) {
1415
22
                    return ret;
1416
22
                }
1417
596
                break;
1418
596
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
1419
1420
596
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1421
596
            case MBEDTLS_TLS_EXT_CID:
1422
339
                MBEDTLS_SSL_DEBUG_MSG(3, ("found CID extension"));
1423
1424
339
                ret = ssl_parse_cid_ext(ssl, ext + 4, ext_size);
1425
339
                if (ret != 0) {
1426
17
                    return ret;
1427
17
                }
1428
322
                break;
1429
322
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1430
1431
322
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1432
918
            case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC:
1433
918
                MBEDTLS_SSL_DEBUG_MSG(3, ("found encrypt then mac extension"));
1434
1435
918
                ret = ssl_parse_encrypt_then_mac_ext(ssl, ext + 4, ext_size);
1436
918
                if (ret != 0) {
1437
17
                    return ret;
1438
17
                }
1439
901
                break;
1440
901
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1441
1442
901
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1443
1.43k
            case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET:
1444
1.43k
                MBEDTLS_SSL_DEBUG_MSG(3, ("found extended master secret extension"));
1445
1446
1.43k
                ret = ssl_parse_extended_ms_ext(ssl, ext + 4, ext_size);
1447
1.43k
                if (ret != 0) {
1448
26
                    return ret;
1449
26
                }
1450
1.40k
                break;
1451
1.40k
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1452
1453
1.40k
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
1454
2.87k
            case MBEDTLS_TLS_EXT_SESSION_TICKET:
1455
2.87k
                MBEDTLS_SSL_DEBUG_MSG(3, ("found session ticket extension"));
1456
1457
2.87k
                ret = ssl_parse_session_ticket_ext(ssl, ext + 4, ext_size);
1458
2.87k
                if (ret != 0) {
1459
0
                    return ret;
1460
0
                }
1461
2.87k
                break;
1462
2.87k
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
1463
1464
2.87k
#if defined(MBEDTLS_SSL_ALPN)
1465
2.87k
            case MBEDTLS_TLS_EXT_ALPN:
1466
771
                MBEDTLS_SSL_DEBUG_MSG(3, ("found alpn extension"));
1467
1468
771
                ret = mbedtls_ssl_parse_alpn_ext(ssl, ext + 4,
1469
771
                                                 ext + 4 + ext_size);
1470
771
                if (ret != 0) {
1471
60
                    return ret;
1472
60
                }
1473
711
                break;
1474
711
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
1475
1476
711
#if defined(MBEDTLS_SSL_DTLS_SRTP)
1477
711
            case MBEDTLS_TLS_EXT_USE_SRTP:
1478
186
                MBEDTLS_SSL_DEBUG_MSG(3, ("found use_srtp extension"));
1479
1480
186
                ret = ssl_parse_use_srtp_ext(ssl, ext + 4, ext_size);
1481
186
                if (ret != 0) {
1482
0
                    return ret;
1483
0
                }
1484
186
                break;
1485
186
#endif /* MBEDTLS_SSL_DTLS_SRTP */
1486
1487
8.50k
            default:
1488
8.50k
                MBEDTLS_SSL_DEBUG_MSG(3, ("unknown extension found: %u (ignoring)",
1489
22.8k
                                          ext_id));
1490
22.8k
        }
1491
1492
22.1k
        ext_len -= 4 + ext_size;
1493
22.1k
        ext += 4 + ext_size;
1494
22.1k
    }
1495
1496
454
#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
454
    if (!sig_hash_alg_ext_present) {
1503
404
        uint16_t *received_sig_algs = ssl->handshake->received_sig_algs;
1504
404
        const uint16_t default_sig_algs[] = {
1505
404
#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED)
1506
404
            MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG(MBEDTLS_SSL_SIG_ECDSA,
1507
404
                                               MBEDTLS_SSL_HASH_SHA1),
1508
404
#endif
1509
404
#if defined(MBEDTLS_RSA_C)
1510
404
            MBEDTLS_SSL_TLS12_SIG_AND_HASH_ALG(MBEDTLS_SSL_SIG_RSA,
1511
404
                                               MBEDTLS_SSL_HASH_SHA1),
1512
404
#endif
1513
404
            MBEDTLS_TLS_SIG_NONE
1514
404
        };
1515
1516
404
        MBEDTLS_STATIC_ASSERT(sizeof(default_sig_algs) / sizeof(default_sig_algs[0])
1517
404
                              <= MBEDTLS_RECEIVED_SIG_ALGS_SIZE,
1518
404
                              "default_sig_algs is too big");
1519
1520
404
        memcpy(received_sig_algs, default_sig_algs, sizeof(default_sig_algs));
1521
404
    }
1522
1523
454
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
1524
1525
    /*
1526
     * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV
1527
     */
1528
13.7k
    for (i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2) {
1529
13.4k
        if (p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO) {
1530
78
            MBEDTLS_SSL_DEBUG_MSG(3, ("received TLS_EMPTY_RENEGOTIATION_INFO "));
1531
78
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1532
78
            if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
1533
0
                MBEDTLS_SSL_DEBUG_MSG(1, ("received RENEGOTIATION SCSV "
1534
0
                                          "during renegotiation"));
1535
0
                mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1536
0
                                               MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1537
0
                return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1538
0
            }
1539
78
#endif
1540
78
            ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION;
1541
78
            break;
1542
78
        }
1543
13.4k
    }
1544
1545
    /*
1546
     * Renegotiation security checks
1547
     */
1548
454
    if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1549
454
        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
454
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1554
454
    else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1555
454
             ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION &&
1556
454
             renegotiation_info_seen == 0) {
1557
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation_info extension missing (secure)"));
1558
0
        handshake_failure = 1;
1559
454
    } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1560
454
               ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1561
454
               ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION) {
1562
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("legacy renegotiation not allowed"));
1563
0
        handshake_failure = 1;
1564
454
    } else if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS &&
1565
454
               ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION &&
1566
454
               renegotiation_info_seen == 1) {
1567
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("renegotiation_info extension present (legacy)"));
1568
0
        handshake_failure = 1;
1569
0
    }
1570
454
#endif /* MBEDTLS_SSL_RENEGOTIATION */
1571
1572
454
    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
454
    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
454
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1586
454
    ssl->handshake->sni_name = NULL;
1587
454
    ssl->handshake->sni_name_len = 0;
1588
454
#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
454
    got_common_suite = 0;
1597
454
    ciphersuites = ssl->conf->ciphersuite_list;
1598
454
    ciphersuite_info = NULL;
1599
1600
454
    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
454
    } else {
1620
74.0k
        for (i = 0; ciphersuites[i] != 0; i++) {
1621
5.03M
            for (j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2) {
1622
4.96M
                if (MBEDTLS_GET_UINT16_BE(p, 0) != ciphersuites[i]) {
1623
4.95M
                    continue;
1624
4.95M
                }
1625
1626
6.94k
                got_common_suite = 1;
1627
1628
6.94k
                if ((ret = ssl_ciphersuite_match(ssl, ciphersuites[i],
1629
6.94k
                                                 &ciphersuite_info)) != 0) {
1630
0
                    return ret;
1631
0
                }
1632
1633
6.94k
                if (ciphersuite_info != NULL) {
1634
202
                    goto have_ciphersuite;
1635
202
                }
1636
6.94k
            }
1637
73.8k
        }
1638
454
    }
1639
1640
252
    if (got_common_suite) {
1641
183
        MBEDTLS_SSL_DEBUG_MSG(1, ("got ciphersuites in common, "
1642
183
                                  "but none of them usable"));
1643
183
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1644
183
                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1645
183
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1646
183
    } else {
1647
69
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no ciphersuites in common"));
1648
69
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
1649
69
                                       MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE);
1650
69
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1651
69
    }
1652
1653
202
have_ciphersuite:
1654
202
    MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %s", ciphersuite_info->name));
1655
1656
202
    ssl->session_negotiate->ciphersuite = ciphersuites[i];
1657
202
    ssl->handshake->ciphersuite_info = ciphersuite_info;
1658
1659
202
    ssl->state++;
1660
1661
202
#if defined(MBEDTLS_SSL_PROTO_DTLS)
1662
202
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
1663
0
        mbedtls_ssl_recv_flight_completed(ssl);
1664
0
    }
1665
202
#endif
1666
1667
    /* Debugging-only output for testsuite */
1668
202
#if defined(MBEDTLS_DEBUG_C)                         && \
1669
202
    defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
1670
202
    mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg(ciphersuite_info);
1671
202
    if (sig_alg != MBEDTLS_PK_NONE) {
1672
0
        unsigned int sig_hash = mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
1673
0
            ssl, mbedtls_ssl_sig_from_pk_alg(sig_alg));
1674
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("client hello v3, signature_algorithm ext: %u",
1675
0
                                  sig_hash));
1676
202
    } else {
1677
202
        MBEDTLS_SSL_DEBUG_MSG(3, ("no hash algorithm for signature algorithm "
1678
202
                                  "%u - should not happen", (unsigned) sig_alg));
1679
202
    }
1680
202
#endif
1681
1682
202
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client hello"));
1683
1684
202
    return 0;
1685
252
}
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
202
{
1692
202
    unsigned char *p = buf;
1693
202
    size_t ext_len;
1694
202
    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
1695
1696
202
    *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
202
    if (ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED) {
1701
202
        return;
1702
202
    }
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
0
    if (end < p || (size_t) (end - p) < (unsigned) (ssl->own_cid_len + 5)) {
1707
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
1708
0
        return;
1709
0
    }
1710
1711
0
    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
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_CID, p, 0);
1719
0
    p += 2;
1720
0
    ext_len = (size_t) ssl->own_cid_len + 1;
1721
0
    MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
1722
0
    p += 2;
1723
1724
0
    *p++ = (uint8_t) ssl->own_cid_len;
1725
0
    memcpy(p, ssl->own_cid, ssl->own_cid_len);
1726
1727
0
    *olen = ssl->own_cid_len + 5;
1728
0
}
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
202
{
1736
202
    unsigned char *p = buf;
1737
202
    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
202
    suite = mbedtls_ssl_ciphersuite_from_id(
1746
202
        ssl->session_negotiate->ciphersuite);
1747
202
    if (suite == NULL) {
1748
0
        ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_DISABLED;
1749
202
    } else {
1750
202
        mbedtls_ssl_mode_t ssl_mode =
1751
202
            mbedtls_ssl_get_mode_from_ciphersuite(
1752
202
                ssl->session_negotiate->encrypt_then_mac,
1753
202
                suite);
1754
1755
202
        if (ssl_mode != MBEDTLS_SSL_MODE_CBC_ETM) {
1756
195
            ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_DISABLED;
1757
195
        }
1758
202
    }
1759
1760
202
    if (ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED) {
1761
195
        *olen = 0;
1762
195
        return;
1763
195
    }
1764
1765
7
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding encrypt then mac extension"));
1766
1767
7
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC, p, 0);
1768
7
    p += 2;
1769
1770
7
    *p++ = 0x00;
1771
7
    *p++ = 0x00;
1772
1773
7
    *olen = 4;
1774
7
}
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
202
{
1782
202
    unsigned char *p = buf;
1783
1784
202
    if (ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED) {
1785
189
        *olen = 0;
1786
189
        return;
1787
189
    }
1788
1789
13
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding extended master secret "
1790
13
                              "extension"));
1791
1792
13
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET, p, 0);
1793
13
    p += 2;
1794
1795
13
    *p++ = 0x00;
1796
13
    *p++ = 0x00;
1797
1798
13
    *olen = 4;
1799
13
}
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
202
{
1807
202
    unsigned char *p = buf;
1808
1809
202
    if (ssl->handshake->new_session_ticket == 0) {
1810
168
        *olen = 0;
1811
168
        return;
1812
168
    }
1813
1814
34
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding session ticket extension"));
1815
1816
34
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SESSION_TICKET, p, 0);
1817
34
    p += 2;
1818
1819
34
    *p++ = 0x00;
1820
34
    *p++ = 0x00;
1821
1822
34
    *olen = 4;
1823
34
}
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
202
{
1830
202
    unsigned char *p = buf;
1831
1832
202
    if (ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION) {
1833
167
        *olen = 0;
1834
167
        return;
1835
167
    }
1836
1837
35
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, secure renegotiation extension"));
1838
1839
35
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_RENEGOTIATION_INFO, p, 0);
1840
35
    p += 2;
1841
1842
35
#if defined(MBEDTLS_SSL_RENEGOTIATION)
1843
35
    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
1844
0
        *p++ = 0x00;
1845
0
        *p++ = (ssl->verify_data_len * 2 + 1) & 0xFF;
1846
0
        *p++ = ssl->verify_data_len * 2 & 0xFF;
1847
1848
0
        memcpy(p, ssl->peer_verify_data, ssl->verify_data_len);
1849
0
        p += ssl->verify_data_len;
1850
0
        memcpy(p, ssl->own_verify_data, ssl->verify_data_len);
1851
0
        p += ssl->verify_data_len;
1852
0
    } else
1853
35
#endif /* MBEDTLS_SSL_RENEGOTIATION */
1854
35
    {
1855
35
        *p++ = 0x00;
1856
35
        *p++ = 0x01;
1857
35
        *p++ = 0x00;
1858
35
    }
1859
1860
35
    *olen = (size_t) (p - buf);
1861
35
}
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
202
{
1868
202
    unsigned char *p = buf;
1869
1870
202
    if (ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE) {
1871
200
        *olen = 0;
1872
200
        return;
1873
200
    }
1874
1875
2
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, max_fragment_length extension"));
1876
1877
2
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH, p, 0);
1878
2
    p += 2;
1879
1880
2
    *p++ = 0x00;
1881
2
    *p++ = 1;
1882
1883
2
    *p++ = ssl->session_negotiate->mfl_code;
1884
1885
2
    *olen = 5;
1886
2
}
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
51
{
1896
51
    unsigned char *p = buf;
1897
51
    ((void) ssl);
1898
1899
51
    if ((ssl->handshake->cli_exts &
1900
51
         MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT) == 0) {
1901
41
        *olen = 0;
1902
41
        return;
1903
41
    }
1904
1905
10
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, supported_point_formats extension"));
1906
1907
10
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS, p, 0);
1908
10
    p += 2;
1909
1910
10
    *p++ = 0x00;
1911
10
    *p++ = 2;
1912
1913
10
    *p++ = 1;
1914
10
    *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED;
1915
1916
10
    *olen = 6;
1917
10
}
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
202
{
1927
202
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1928
202
    unsigned char *p = buf;
1929
202
    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
1930
202
    size_t kkpp_len;
1931
1932
202
    *olen = 0;
1933
1934
    /* Skip costly computation if not needed */
1935
202
    if (ssl->handshake->ciphersuite_info->key_exchange !=
1936
202
        MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
1937
202
        return;
1938
202
    }
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
202
{
1982
202
    size_t mki_len = 0, ext_len = 0;
1983
202
    uint16_t profile_value = 0;
1984
202
    const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
1985
1986
202
    *olen = 0;
1987
1988
202
    if ((ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) ||
1989
202
        (ssl->dtls_srtp_info.chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET)) {
1990
202
        return;
1991
202
    }
1992
1993
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding use_srtp extension"));
1994
1995
0
    if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED) {
1996
0
        mki_len = ssl->dtls_srtp_info.mki_len;
1997
0
    }
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
0
    if ((size_t) (end - buf) < mki_len + 9) {
2008
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("buffer too small"));
2009
0
        return;
2010
0
    }
2011
2012
    /* extension */
2013
0
    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
0
    ext_len = 5 + mki_len;
2019
0
    MBEDTLS_PUT_UINT16_BE(ext_len, buf, 2);
2020
2021
    /* protection profile length: 2 */
2022
0
    buf[4] = 0x00;
2023
0
    buf[5] = 0x02;
2024
0
    profile_value = mbedtls_ssl_check_srtp_profile_value(
2025
0
        ssl->dtls_srtp_info.chosen_dtls_srtp_profile);
2026
0
    if (profile_value != MBEDTLS_TLS_SRTP_UNSET) {
2027
0
        MBEDTLS_PUT_UINT16_BE(profile_value, buf, 6);
2028
0
    } else {
2029
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("use_srtp extension invalid profile"));
2030
0
        return;
2031
0
    }
2032
2033
0
    buf[8] = mki_len & 0xFF;
2034
0
    memcpy(&buf[9], ssl->dtls_srtp_info.mki_value, mki_len);
2035
2036
0
    *olen = 9 + mki_len;
2037
0
}
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
202
{
2110
202
    int ret;
2111
202
    mbedtls_ssl_session session_tmp;
2112
202
    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
202
    if (ssl->handshake->resume == 1) {
2117
0
        return;
2118
0
    }
2119
202
    if (session->id_len == 0) {
2120
122
        return;
2121
122
    }
2122
80
    if (ssl->conf->f_get_cache == NULL) {
2123
80
        return;
2124
80
    }
2125
0
#if defined(MBEDTLS_SSL_RENEGOTIATION)
2126
0
    if (ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE) {
2127
0
        return;
2128
0
    }
2129
0
#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
202
{
2162
202
#if defined(MBEDTLS_HAVE_TIME)
2163
202
    mbedtls_time_t t;
2164
202
#endif
2165
202
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2166
202
    size_t olen, ext_len = 0, n;
2167
202
    unsigned char *buf, *p;
2168
2169
202
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello"));
2170
2171
202
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
2172
202
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
2173
202
        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
202
#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
202
    buf = ssl->out_msg;
2189
202
    p = buf + 4;
2190
2191
202
    mbedtls_ssl_write_version(p, ssl->conf->transport, ssl->tls_version);
2192
202
    p += 2;
2193
2194
202
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen version: [%d:%d]",
2195
202
                              buf[4], buf[5]));
2196
2197
202
#if defined(MBEDTLS_HAVE_TIME)
2198
202
    t = mbedtls_time(NULL);
2199
202
    MBEDTLS_PUT_UINT32_BE(t, p, 0);
2200
202
    p += 4;
2201
2202
202
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, current time: %" MBEDTLS_PRINTF_LONGLONG,
2203
202
                              (long long) t));
2204
#else
2205
    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 4)) != 0) {
2206
        return ret;
2207
    }
2208
2209
    p += 4;
2210
#endif /* MBEDTLS_HAVE_TIME */
2211
2212
202
    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, p, 20)) != 0) {
2213
0
        return ret;
2214
0
    }
2215
202
    p += 20;
2216
2217
202
#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
202
    if (mbedtls_ssl_conf_is_tls13_enabled(ssl->conf)) {
2226
202
        static const unsigned char magic_tls12_downgrade_string[] =
2227
202
        { 'D', 'O', 'W', 'N', 'G', 'R', 'D', 1 };
2228
2229
202
        MBEDTLS_STATIC_ASSERT(
2230
202
            sizeof(magic_tls12_downgrade_string) == 8,
2231
202
            "magic_tls12_downgrade_string does not have the expected size");
2232
2233
202
        memcpy(p, magic_tls12_downgrade_string,
2234
202
               sizeof(magic_tls12_downgrade_string));
2235
202
    } else
2236
0
#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
202
    p += 8;
2243
2244
202
    memcpy(ssl->handshake->randbytes + 32, buf + 6, 32);
2245
2246
202
    MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes", buf + 6, 32);
2247
2248
202
    ssl_handle_id_based_session_resumption(ssl);
2249
2250
202
    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
202
        ssl->state++;
2256
2257
202
#if defined(MBEDTLS_HAVE_TIME)
2258
202
        ssl->session_negotiate->start = mbedtls_time(NULL);
2259
202
#endif
2260
2261
202
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
2262
202
        if (ssl->handshake->new_session_ticket != 0) {
2263
34
            ssl->session_negotiate->id_len = n = 0;
2264
34
            memset(ssl->session_negotiate->id, 0, 32);
2265
34
        } else
2266
168
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
2267
168
        {
2268
168
            ssl->session_negotiate->id_len = n = 32;
2269
168
            if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, ssl->session_negotiate->id,
2270
168
                                        n)) != 0) {
2271
0
                return ret;
2272
0
            }
2273
168
        }
2274
202
    } 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
202
    *p++ = (unsigned char) ssl->session_negotiate->id_len;
2296
202
    memcpy(p, ssl->session_negotiate->id, ssl->session_negotiate->id_len);
2297
202
    p += ssl->session_negotiate->id_len;
2298
2299
202
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, session id len.: %" MBEDTLS_PRINTF_SIZET, n));
2300
202
    MBEDTLS_SSL_DEBUG_BUF(3,   "server hello, session id", buf + 39, n);
2301
202
    MBEDTLS_SSL_DEBUG_MSG(3, ("%s session has been resumed",
2302
202
                              ssl->handshake->resume ? "a" : "no"));
2303
2304
202
    MBEDTLS_PUT_UINT16_BE(ssl->session_negotiate->ciphersuite, p, 0);
2305
202
    p += 2;
2306
202
    *p++ = MBEDTLS_BYTE_0(MBEDTLS_SSL_COMPRESS_NULL);
2307
2308
202
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, chosen ciphersuite: %s",
2309
202
                              mbedtls_ssl_get_ciphersuite_name(ssl->session_negotiate->ciphersuite)));
2310
202
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, compress alg.: 0x%02X",
2311
202
                              (unsigned int) MBEDTLS_SSL_COMPRESS_NULL));
2312
2313
    /*
2314
     *  First write extensions, then the total length
2315
     */
2316
202
    ssl_write_renegotiation_ext(ssl, p + 2 + ext_len, &olen);
2317
202
    ext_len += olen;
2318
2319
202
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
2320
202
    ssl_write_max_fragment_length_ext(ssl, p + 2 + ext_len, &olen);
2321
202
    ext_len += olen;
2322
202
#endif
2323
2324
202
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
2325
202
    ssl_write_cid_ext(ssl, p + 2 + ext_len, &olen);
2326
202
    ext_len += olen;
2327
202
#endif
2328
2329
202
#if defined(MBEDTLS_SSL_SOME_SUITES_USE_CBC_ETM)
2330
202
    ssl_write_encrypt_then_mac_ext(ssl, p + 2 + ext_len, &olen);
2331
202
    ext_len += olen;
2332
202
#endif
2333
2334
202
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
2335
202
    ssl_write_extended_ms_ext(ssl, p + 2 + ext_len, &olen);
2336
202
    ext_len += olen;
2337
202
#endif
2338
2339
202
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
2340
202
    ssl_write_session_ticket_ext(ssl, p + 2 + ext_len, &olen);
2341
202
    ext_len += olen;
2342
202
#endif
2343
2344
202
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
2345
202
    defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
2346
202
    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2347
202
    const mbedtls_ssl_ciphersuite_t *suite =
2348
202
        mbedtls_ssl_ciphersuite_from_id(ssl->session_negotiate->ciphersuite);
2349
202
    if (suite != NULL && mbedtls_ssl_ciphersuite_uses_ec(suite)) {
2350
51
        ssl_write_supported_point_formats_ext(ssl, p + 2 + ext_len, &olen);
2351
51
        ext_len += olen;
2352
51
    }
2353
202
#endif
2354
2355
202
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2356
202
    ssl_write_ecjpake_kkpp_ext(ssl, p + 2 + ext_len, &olen);
2357
202
    ext_len += olen;
2358
202
#endif
2359
2360
202
#if defined(MBEDTLS_SSL_ALPN)
2361
202
    unsigned char *end = buf + MBEDTLS_SSL_OUT_CONTENT_LEN - 4;
2362
202
    if ((ret = mbedtls_ssl_write_alpn_ext(ssl, p + 2 + ext_len, end, &olen))
2363
202
        != 0) {
2364
0
        return ret;
2365
0
    }
2366
2367
202
    ext_len += olen;
2368
202
#endif
2369
2370
202
#if defined(MBEDTLS_SSL_DTLS_SRTP)
2371
202
    ssl_write_use_srtp_ext(ssl, p + 2 + ext_len, &olen);
2372
202
    ext_len += olen;
2373
202
#endif
2374
2375
202
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, total extension length: %" MBEDTLS_PRINTF_SIZET,
2376
202
                              ext_len));
2377
2378
202
    if (ext_len > 0) {
2379
76
        MBEDTLS_PUT_UINT16_BE(ext_len, p, 0);
2380
76
        p += 2 + ext_len;
2381
76
    }
2382
2383
202
    ssl->out_msglen  = (size_t) (p - buf);
2384
202
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2385
202
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO;
2386
2387
202
    ret = mbedtls_ssl_write_handshake_msg(ssl);
2388
2389
202
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2390
2391
202
    return ret;
2392
202
}
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
199
{
2416
199
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2417
199
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2418
199
        ssl->handshake->ciphersuite_info;
2419
199
    uint16_t dn_size, total_dn_size; /* excluding length bytes */
2420
199
    size_t ct_len, sa_len; /* including length bytes */
2421
199
    unsigned char *buf, *p;
2422
199
    const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN;
2423
199
    const mbedtls_x509_crt *crt;
2424
199
    int authmode;
2425
2426
199
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2427
2428
199
    ssl->state++;
2429
2430
199
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2431
199
    if (ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET) {
2432
0
        authmode = ssl->handshake->sni_authmode;
2433
0
    } else
2434
199
#endif
2435
199
    authmode = ssl->conf->authmode;
2436
2437
199
    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info) ||
2438
199
        authmode == MBEDTLS_SSL_VERIFY_NONE) {
2439
199
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
2440
199
        return 0;
2441
199
    }
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
0
#if defined(MBEDTLS_RSA_C)
2467
0
    p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN;
2468
0
#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
0
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2535
0
        if (ssl->handshake->dn_hints != NULL) {
2536
0
            crt = ssl->handshake->dn_hints;
2537
0
        } else
2538
0
#endif
2539
0
        if (ssl->conf->dn_hints != NULL) {
2540
0
            crt = ssl->conf->dn_hints;
2541
0
        } else
2542
0
#endif
2543
0
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2544
0
        if (ssl->handshake->sni_ca_chain != NULL) {
2545
0
            crt = ssl->handshake->sni_ca_chain;
2546
0
        } else
2547
0
#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
0
{
2591
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2592
0
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
2593
0
    mbedtls_pk_context *pk;
2594
0
    mbedtls_pk_type_t pk_type;
2595
0
    psa_key_attributes_t key_attributes = PSA_KEY_ATTRIBUTES_INIT;
2596
0
    unsigned char buf[PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)];
2597
0
    size_t key_len;
2598
0
#if !defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2599
0
    uint16_t tls_id = 0;
2600
0
    psa_key_type_t key_type = PSA_KEY_TYPE_NONE;
2601
0
    mbedtls_ecp_group_id grp_id;
2602
0
    mbedtls_ecp_keypair *key;
2603
0
#endif /* !MBEDTLS_PK_USE_PSA_EC_DATA */
2604
2605
0
    pk = mbedtls_ssl_own_key(ssl);
2606
2607
0
    if (pk == NULL) {
2608
0
        return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2609
0
    }
2610
2611
0
    pk_type = mbedtls_pk_get_type(pk);
2612
2613
0
    switch (pk_type) {
2614
0
        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
0
            if (!mbedtls_pk_can_do(pk, MBEDTLS_PK_ECKEY)) {
2621
0
                return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2622
0
            }
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
0
            status = psa_get_key_attributes(pk->priv_id, &key_attributes);
2627
0
            if (status != PSA_SUCCESS) {
2628
0
                ret = PSA_TO_MBEDTLS_ERR(status);
2629
0
                goto exit;
2630
0
            }
2631
0
            ssl->handshake->xxdh_psa_type = psa_get_key_type(&key_attributes);
2632
0
            ssl->handshake->xxdh_psa_bits = psa_get_key_bits(&key_attributes);
2633
2634
#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2635
            if (pk_type != MBEDTLS_PK_OPAQUE) {
2636
                /* PK_ECKEY[_DH] and PK_ECDSA instead as parsed from the PK
2637
                 * module and only have ECDSA capabilities. Since we need
2638
                 * them for ECDH later, we export and then re-import them with
2639
                 * proper flags and algorithm. Of course We also set key's type
2640
                 * and bits that we just got above. */
2641
                key_attributes = psa_key_attributes_init();
2642
                psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
2643
                psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
2644
                psa_set_key_type(&key_attributes,
2645
                                 PSA_KEY_TYPE_ECC_KEY_PAIR(ssl->handshake->xxdh_psa_type));
2646
                psa_set_key_bits(&key_attributes, ssl->handshake->xxdh_psa_bits);
2647
2648
                status = psa_export_key(pk->priv_id, buf, sizeof(buf), &key_len);
2649
                if (status != PSA_SUCCESS) {
2650
                    ret = PSA_TO_MBEDTLS_ERR(status);
2651
                    goto exit;
2652
                }
2653
                status = psa_import_key(&key_attributes, buf, key_len,
2654
                                        &ssl->handshake->xxdh_psa_privkey);
2655
                if (status != PSA_SUCCESS) {
2656
                    ret = PSA_TO_MBEDTLS_ERR(status);
2657
                    goto exit;
2658
                }
2659
2660
                /* Set this key as owned by the TLS library: it will be its duty
2661
                 * to clear it exit. */
2662
                ssl->handshake->xxdh_psa_privkey_is_external = 0;
2663
2664
                ret = 0;
2665
                break;
2666
            }
2667
#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
2668
2669
            /* Opaque key is created by the user (externally from Mbed TLS)
2670
             * so we assume it already has the right algorithm and flags
2671
             * set. Just copy its ID as reference. */
2672
0
            ssl->handshake->xxdh_psa_privkey = pk->priv_id;
2673
0
            ssl->handshake->xxdh_psa_privkey_is_external = 1;
2674
0
            ret = 0;
2675
0
            break;
2676
2677
0
#if !defined(MBEDTLS_PK_USE_PSA_EC_DATA)
2678
0
        case MBEDTLS_PK_ECKEY:
2679
0
        case MBEDTLS_PK_ECKEY_DH:
2680
0
        case MBEDTLS_PK_ECDSA:
2681
0
            key = mbedtls_pk_ec_rw(*pk);
2682
0
            grp_id = mbedtls_pk_get_ec_group_id(pk);
2683
0
            if (grp_id == MBEDTLS_ECP_DP_NONE) {
2684
0
                return MBEDTLS_ERR_ECP_BAD_INPUT_DATA;
2685
0
            }
2686
0
            tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(grp_id);
2687
0
            if (tls_id == 0) {
2688
                /* This elliptic curve is not supported */
2689
0
                return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2690
0
            }
2691
2692
            /* If the above conversion to TLS ID was fine, then also this one will
2693
               be, so there is no need to check the return value here */
2694
0
            mbedtls_ssl_get_psa_curve_info_from_tls_id(tls_id, &key_type,
2695
0
                                                       &ssl->handshake->xxdh_psa_bits);
2696
2697
0
            ssl->handshake->xxdh_psa_type = key_type;
2698
2699
0
            key_attributes = psa_key_attributes_init();
2700
0
            psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
2701
0
            psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
2702
0
            psa_set_key_type(&key_attributes,
2703
0
                             PSA_KEY_TYPE_ECC_KEY_PAIR(ssl->handshake->xxdh_psa_type));
2704
0
            psa_set_key_bits(&key_attributes, ssl->handshake->xxdh_psa_bits);
2705
2706
0
            ret = mbedtls_ecp_write_key_ext(key, &key_len, buf, sizeof(buf));
2707
0
            if (ret != 0) {
2708
0
                mbedtls_platform_zeroize(buf, sizeof(buf));
2709
0
                break;
2710
0
            }
2711
2712
0
            status = psa_import_key(&key_attributes, buf, key_len,
2713
0
                                    &ssl->handshake->xxdh_psa_privkey);
2714
0
            if (status != PSA_SUCCESS) {
2715
0
                ret = PSA_TO_MBEDTLS_ERR(status);
2716
0
                mbedtls_platform_zeroize(buf, sizeof(buf));
2717
0
                break;
2718
0
            }
2719
2720
0
            mbedtls_platform_zeroize(buf, sizeof(buf));
2721
0
            ret = 0;
2722
0
            break;
2723
0
#endif /* !MBEDTLS_PK_USE_PSA_EC_DATA */
2724
0
        default:
2725
0
            ret = MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2726
0
    }
2727
2728
0
exit:
2729
0
    psa_reset_key_attributes(&key_attributes);
2730
0
    mbedtls_platform_zeroize(buf, sizeof(buf));
2731
2732
0
    return ret;
2733
0
}
2734
#else /* MBEDTLS_USE_PSA_CRYPTO */
2735
MBEDTLS_CHECK_RETURN_CRITICAL
2736
static int ssl_get_ecdh_params_from_cert(mbedtls_ssl_context *ssl)
2737
0
{
2738
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2739
2740
0
    const mbedtls_pk_context *private_key = mbedtls_ssl_own_key(ssl);
2741
0
    if (private_key == NULL) {
2742
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no server private key"));
2743
0
        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
2744
0
    }
2745
2746
0
    if (!mbedtls_pk_can_do(private_key, MBEDTLS_PK_ECKEY)) {
2747
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("server key not ECDH capable"));
2748
0
        return MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH;
2749
0
    }
2750
2751
0
    if ((ret = mbedtls_ecdh_get_params(&ssl->handshake->ecdh_ctx,
2752
0
                                       mbedtls_pk_ec_ro(*mbedtls_ssl_own_key(ssl)),
2753
0
                                       MBEDTLS_ECDH_OURS)) != 0) {
2754
0
        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ecdh_get_params"), ret);
2755
0
        return ret;
2756
0
    }
2757
2758
0
    return 0;
2759
0
}
2760
#endif /* MBEDTLS_USE_PSA_CRYPTO */
2761
#endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||
2762
          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
2763
2764
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
2765
    defined(MBEDTLS_SSL_ASYNC_PRIVATE)
2766
MBEDTLS_CHECK_RETURN_CRITICAL
2767
static int ssl_resume_server_key_exchange(mbedtls_ssl_context *ssl,
2768
                                          size_t *signature_len)
2769
0
{
2770
    /* Append the signature to ssl->out_msg, leaving 2 bytes for the
2771
     * signature length which will be added in ssl_write_server_key_exchange
2772
     * after the call to ssl_prepare_server_key_exchange.
2773
     * ssl_write_server_key_exchange also takes care of incrementing
2774
     * ssl->out_msglen. */
2775
0
    unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2;
2776
0
    size_t sig_max_len = (ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN
2777
0
                          - sig_start);
2778
0
    int ret = ssl->conf->f_async_resume(ssl,
2779
0
                                        sig_start, signature_len, sig_max_len);
2780
0
    if (ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
2781
0
        ssl->handshake->async_in_progress = 0;
2782
0
        mbedtls_ssl_set_async_operation_data(ssl, NULL);
2783
0
    }
2784
0
    MBEDTLS_SSL_DEBUG_RET(2, "ssl_resume_server_key_exchange", ret);
2785
0
    return ret;
2786
0
}
2787
#endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
2788
          defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
2789
2790
/* Prepare the ServerKeyExchange message, up to and including
2791
 * calculating the signature if any, but excluding formatting the
2792
 * signature and sending the message. */
2793
MBEDTLS_CHECK_RETURN_CRITICAL
2794
static int ssl_prepare_server_key_exchange(mbedtls_ssl_context *ssl,
2795
                                           size_t *signature_len)
2796
127
{
2797
127
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2798
127
        ssl->handshake->ciphersuite_info;
2799
2800
127
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED)
2801
127
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2802
127
    unsigned char *dig_signed = NULL;
2803
127
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
2804
127
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */
2805
2806
127
    (void) ciphersuite_info; /* unused in some configurations */
2807
#if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2808
    (void) signature_len;
2809
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
2810
2811
127
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2812
127
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
2813
127
    size_t out_buf_len = ssl->out_buf_len - (size_t) (ssl->out_msg - ssl->out_buf);
2814
#else
2815
    size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN - (size_t) (ssl->out_msg - ssl->out_buf);
2816
#endif
2817
127
#endif
2818
2819
127
    ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */
2820
2821
    /*
2822
     *
2823
     * Part 1: Provide key exchange parameters for chosen ciphersuite.
2824
     *
2825
     */
2826
2827
    /*
2828
     * - ECJPAKE key exchanges
2829
     */
2830
127
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
2831
127
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
2832
0
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2833
#if defined(MBEDTLS_USE_PSA_CRYPTO)
2834
        unsigned char *out_p = ssl->out_msg + ssl->out_msglen;
2835
        unsigned char *end_p = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN -
2836
                               ssl->out_msglen;
2837
        size_t output_offset = 0;
2838
        size_t output_len = 0;
2839
2840
        /*
2841
         * The first 3 bytes are:
2842
         * [0] MBEDTLS_ECP_TLS_NAMED_CURVE
2843
         * [1, 2] elliptic curve's TLS ID
2844
         *
2845
         * However since we only support secp256r1 for now, we hardcode its
2846
         * TLS ID here
2847
         */
2848
        uint16_t tls_id = mbedtls_ssl_get_tls_id_from_ecp_group_id(
2849
            MBEDTLS_ECP_DP_SECP256R1);
2850
        if (tls_id == 0) {
2851
            return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2852
        }
2853
        *out_p = MBEDTLS_ECP_TLS_NAMED_CURVE;
2854
        MBEDTLS_PUT_UINT16_BE(tls_id, out_p, 1);
2855
        output_offset += 3;
2856
2857
        ret = mbedtls_psa_ecjpake_write_round(&ssl->handshake->psa_pake_ctx,
2858
                                              out_p + output_offset,
2859
                                              end_p - out_p - output_offset, &output_len,
2860
                                              MBEDTLS_ECJPAKE_ROUND_TWO);
2861
        if (ret != 0) {
2862
            psa_destroy_key(ssl->handshake->psa_pake_password);
2863
            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
2864
            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_output", ret);
2865
            return ret;
2866
        }
2867
2868
        output_offset += output_len;
2869
        ssl->out_msglen += output_offset;
2870
#else
2871
0
        size_t len = 0;
2872
2873
0
        ret = mbedtls_ecjpake_write_round_two(
2874
0
            &ssl->handshake->ecjpake_ctx,
2875
0
            ssl->out_msg + ssl->out_msglen,
2876
0
            MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len,
2877
0
            ssl->conf->f_rng, ssl->conf->p_rng);
2878
0
        if (ret != 0) {
2879
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_write_round_two", ret);
2880
0
            return ret;
2881
0
        }
2882
2883
0
        ssl->out_msglen += len;
2884
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
2885
0
    }
2886
127
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
2887
2888
    /*
2889
     * For (EC)DHE key exchanges with PSK, parameters are prefixed by support
2890
     * identity hint (RFC 4279, Sec. 3). Until someone needs this feature,
2891
     * we use empty support identity hints here.
2892
     **/
2893
127
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)   || \
2894
127
    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
2895
127
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ||
2896
127
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
2897
127
        ssl->out_msg[ssl->out_msglen++] = 0x00;
2898
127
        ssl->out_msg[ssl->out_msglen++] = 0x00;
2899
127
    }
2900
127
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED ||
2901
          MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
2902
2903
    /*
2904
     * - DHE key exchanges
2905
     */
2906
127
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED)
2907
127
    if (mbedtls_ssl_ciphersuite_uses_dhe(ciphersuite_info)) {
2908
76
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2909
76
        size_t len = 0;
2910
2911
76
        if (ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL) {
2912
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("no DH parameters set"));
2913
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2914
0
        }
2915
2916
        /*
2917
         * Ephemeral DH parameters:
2918
         *
2919
         * struct {
2920
         *     opaque dh_p<1..2^16-1>;
2921
         *     opaque dh_g<1..2^16-1>;
2922
         *     opaque dh_Ys<1..2^16-1>;
2923
         * } ServerDHParams;
2924
         */
2925
76
        if ((ret = mbedtls_dhm_set_group(&ssl->handshake->dhm_ctx,
2926
76
                                         &ssl->conf->dhm_P,
2927
76
                                         &ssl->conf->dhm_G)) != 0) {
2928
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_set_group", ret);
2929
0
            return ret;
2930
0
        }
2931
2932
76
        if ((ret = mbedtls_dhm_make_params(
2933
76
                 &ssl->handshake->dhm_ctx,
2934
76
                 (int) mbedtls_dhm_get_len(&ssl->handshake->dhm_ctx),
2935
76
                 ssl->out_msg + ssl->out_msglen, &len,
2936
76
                 ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2937
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_make_params", ret);
2938
0
            return ret;
2939
0
        }
2940
2941
76
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
2942
76
        dig_signed = ssl->out_msg + ssl->out_msglen;
2943
76
#endif
2944
2945
76
        ssl->out_msglen += len;
2946
2947
76
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: X ", &ssl->handshake->dhm_ctx.X);
2948
76
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: P ", &ssl->handshake->dhm_ctx.P);
2949
76
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: G ", &ssl->handshake->dhm_ctx.G);
2950
76
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GX", &ssl->handshake->dhm_ctx.GX);
2951
76
    }
2952
127
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */
2953
2954
    /*
2955
     * - ECDHE key exchanges
2956
     */
2957
127
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
2958
127
    if (mbedtls_ssl_ciphersuite_uses_ecdhe(ciphersuite_info)) {
2959
        /*
2960
         * Ephemeral ECDH parameters:
2961
         *
2962
         * struct {
2963
         *     ECParameters curve_params;
2964
         *     ECPoint      public;
2965
         * } ServerECDHParams;
2966
         */
2967
51
        uint16_t *curr_tls_id = ssl->handshake->curves_tls_id;
2968
51
        const uint16_t *group_list = mbedtls_ssl_get_groups(ssl);
2969
51
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2970
51
        size_t len = 0;
2971
2972
        /* Match our preference list against the offered curves */
2973
51
        if ((group_list == NULL) || (curr_tls_id == NULL)) {
2974
0
            return MBEDTLS_ERR_SSL_BAD_CONFIG;
2975
0
        }
2976
258
        for (; *group_list != 0; group_list++) {
2977
255
            for (curr_tls_id = ssl->handshake->curves_tls_id;
2978
898
                 *curr_tls_id != 0; curr_tls_id++) {
2979
691
                if (*curr_tls_id == *group_list) {
2980
48
                    goto curve_matching_done;
2981
48
                }
2982
691
            }
2983
255
        }
2984
2985
51
curve_matching_done:
2986
51
        if (*curr_tls_id == 0) {
2987
3
            MBEDTLS_SSL_DEBUG_MSG(1, ("no matching curve for ECDHE"));
2988
3
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2989
3
        }
2990
2991
48
        MBEDTLS_SSL_DEBUG_MSG(2, ("ECDHE curve: %s",
2992
48
                                  mbedtls_ssl_get_curve_name_from_tls_id(*curr_tls_id)));
2993
2994
#if defined(MBEDTLS_USE_PSA_CRYPTO)
2995
        psa_status_t status = PSA_ERROR_GENERIC_ERROR;
2996
        psa_key_attributes_t key_attributes;
2997
        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
2998
        uint8_t *p = ssl->out_msg + ssl->out_msglen;
2999
        const size_t header_size = 4; // curve_type(1), namedcurve(2),
3000
                                      // data length(1)
3001
        const size_t data_length_size = 1;
3002
        psa_key_type_t key_type = PSA_KEY_TYPE_NONE;
3003
        size_t ec_bits = 0;
3004
3005
        MBEDTLS_SSL_DEBUG_MSG(1, ("Perform PSA-based ECDH computation."));
3006
3007
        /* Convert EC's TLS ID to PSA key type. */
3008
        if (mbedtls_ssl_get_psa_curve_info_from_tls_id(*curr_tls_id,
3009
                                                       &key_type,
3010
                                                       &ec_bits) == PSA_ERROR_NOT_SUPPORTED) {
3011
            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid ecc group parse."));
3012
            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
3013
        }
3014
        handshake->xxdh_psa_type = key_type;
3015
        handshake->xxdh_psa_bits = ec_bits;
3016
3017
        key_attributes = psa_key_attributes_init();
3018
        psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
3019
        psa_set_key_algorithm(&key_attributes, PSA_ALG_ECDH);
3020
        psa_set_key_type(&key_attributes, handshake->xxdh_psa_type);
3021
        psa_set_key_bits(&key_attributes, handshake->xxdh_psa_bits);
3022
3023
        /*
3024
         * ECParameters curve_params
3025
         *
3026
         * First byte is curve_type, always named_curve
3027
         */
3028
        *p++ = MBEDTLS_ECP_TLS_NAMED_CURVE;
3029
3030
        /*
3031
         * Next two bytes are the namedcurve value
3032
         */
3033
        MBEDTLS_PUT_UINT16_BE(*curr_tls_id, p, 0);
3034
        p += 2;
3035
3036
        /* Generate ECDH private key. */
3037
        status = psa_generate_key(&key_attributes,
3038
                                  &handshake->xxdh_psa_privkey);
3039
        if (status != PSA_SUCCESS) {
3040
            ret = PSA_TO_MBEDTLS_ERR(status);
3041
            MBEDTLS_SSL_DEBUG_RET(1, "psa_generate_key", ret);
3042
            return ret;
3043
        }
3044
3045
        /*
3046
         * ECPoint  public
3047
         *
3048
         * First byte is data length.
3049
         * It will be filled later. p holds now the data length location.
3050
         */
3051
3052
        /* Export the public part of the ECDH private key from PSA.
3053
         * Make one byte space for the length.
3054
         */
3055
        unsigned char *own_pubkey = p + data_length_size;
3056
3057
        size_t own_pubkey_max_len = (size_t) (MBEDTLS_SSL_OUT_CONTENT_LEN
3058
                                              - (own_pubkey - ssl->out_msg));
3059
3060
        status = psa_export_public_key(handshake->xxdh_psa_privkey,
3061
                                       own_pubkey, own_pubkey_max_len,
3062
                                       &len);
3063
        if (status != PSA_SUCCESS) {
3064
            ret = PSA_TO_MBEDTLS_ERR(status);
3065
            MBEDTLS_SSL_DEBUG_RET(1, "psa_export_public_key", ret);
3066
            (void) psa_destroy_key(handshake->xxdh_psa_privkey);
3067
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3068
            return ret;
3069
        }
3070
3071
        /* Store the length of the exported public key. */
3072
        *p = (uint8_t) len;
3073
3074
        /* Determine full message length. */
3075
        len += header_size;
3076
#else
3077
48
        mbedtls_ecp_group_id curr_grp_id =
3078
48
            mbedtls_ssl_get_ecp_group_id_from_tls_id(*curr_tls_id);
3079
3080
48
        if ((ret = mbedtls_ecdh_setup(&ssl->handshake->ecdh_ctx,
3081
48
                                      curr_grp_id)) != 0) {
3082
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecp_group_load", ret);
3083
0
            return ret;
3084
0
        }
3085
3086
48
        if ((ret = mbedtls_ecdh_make_params(
3087
48
                 &ssl->handshake->ecdh_ctx, &len,
3088
48
                 ssl->out_msg + ssl->out_msglen,
3089
48
                 MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen,
3090
48
                 ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3091
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_make_params", ret);
3092
0
            return ret;
3093
0
        }
3094
3095
48
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3096
48
                               MBEDTLS_DEBUG_ECDH_Q);
3097
48
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3098
3099
48
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3100
48
        dig_signed = ssl->out_msg + ssl->out_msglen;
3101
48
#endif
3102
3103
48
        ssl->out_msglen += len;
3104
48
    }
3105
124
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */
3106
3107
    /*
3108
     *
3109
     * Part 2: For key exchanges involving the server signing the
3110
     *         exchange parameters, compute and add the signature here.
3111
     *
3112
     */
3113
124
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3114
124
    if (mbedtls_ssl_ciphersuite_uses_server_signature(ciphersuite_info)) {
3115
0
        if (dig_signed == NULL) {
3116
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3117
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3118
0
        }
3119
3120
0
        size_t dig_signed_len = (size_t) (ssl->out_msg + ssl->out_msglen - dig_signed);
3121
0
        size_t hashlen = 0;
3122
0
        unsigned char hash[MBEDTLS_MD_MAX_SIZE];
3123
3124
0
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3125
3126
        /*
3127
         * 2.1: Choose hash algorithm:
3128
         *      For TLS 1.2, obey signature-hash-algorithm extension
3129
         *      to choose appropriate hash.
3130
         */
3131
3132
0
        mbedtls_pk_type_t sig_alg =
3133
0
            mbedtls_ssl_get_ciphersuite_sig_pk_alg(ciphersuite_info);
3134
3135
0
        unsigned char sig_hash =
3136
0
            (unsigned char) mbedtls_ssl_tls12_get_preferred_hash_for_sig_alg(
3137
0
                ssl, mbedtls_ssl_sig_from_pk_alg(sig_alg));
3138
3139
0
        mbedtls_md_type_t md_alg = mbedtls_ssl_md_alg_from_hash(sig_hash);
3140
3141
        /*    For TLS 1.2, obey signature-hash-algorithm extension
3142
         *    (RFC 5246, Sec. 7.4.1.4.1). */
3143
0
        if (sig_alg == MBEDTLS_PK_NONE || md_alg == MBEDTLS_MD_NONE) {
3144
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3145
            /* (... because we choose a cipher suite
3146
             *      only if there is a matching hash.) */
3147
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3148
0
        }
3149
3150
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("pick hash algorithm %u for signing", (unsigned) md_alg));
3151
3152
        /*
3153
         * 2.2: Compute the hash to be signed
3154
         */
3155
0
        if (md_alg != MBEDTLS_MD_NONE) {
3156
0
            ret = mbedtls_ssl_get_key_exchange_md_tls1_2(ssl, hash, &hashlen,
3157
0
                                                         dig_signed,
3158
0
                                                         dig_signed_len,
3159
0
                                                         md_alg);
3160
0
            if (ret != 0) {
3161
0
                return ret;
3162
0
            }
3163
0
        } else {
3164
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3165
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3166
0
        }
3167
3168
0
        MBEDTLS_SSL_DEBUG_BUF(3, "parameters hash", hash, hashlen);
3169
3170
        /*
3171
         * 2.3: Compute and add the signature
3172
         */
3173
        /*
3174
         * We need to specify signature and hash algorithm explicitly through
3175
         * a prefix to the signature.
3176
         *
3177
         * struct {
3178
         *    HashAlgorithm hash;
3179
         *    SignatureAlgorithm signature;
3180
         * } SignatureAndHashAlgorithm;
3181
         *
3182
         * struct {
3183
         *    SignatureAndHashAlgorithm algorithm;
3184
         *    opaque signature<0..2^16-1>;
3185
         * } DigitallySigned;
3186
         *
3187
         */
3188
3189
0
        ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_hash_from_md_alg(md_alg);
3190
0
        ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_sig_from_pk_alg(sig_alg);
3191
3192
0
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3193
0
        if (ssl->conf->f_async_sign_start != NULL) {
3194
0
            ret = ssl->conf->f_async_sign_start(ssl,
3195
0
                                                mbedtls_ssl_own_cert(ssl),
3196
0
                                                md_alg, hash, hashlen);
3197
0
            switch (ret) {
3198
0
                case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3199
                    /* act as if f_async_sign was null */
3200
0
                    break;
3201
0
                case 0:
3202
0
                    ssl->handshake->async_in_progress = 1;
3203
0
                    return ssl_resume_server_key_exchange(ssl, signature_len);
3204
0
                case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3205
0
                    ssl->handshake->async_in_progress = 1;
3206
0
                    return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
3207
0
                default:
3208
0
                    MBEDTLS_SSL_DEBUG_RET(1, "f_async_sign_start", ret);
3209
0
                    return ret;
3210
0
            }
3211
0
        }
3212
0
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3213
3214
0
        if (mbedtls_ssl_own_key(ssl) == NULL) {
3215
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("got no private key"));
3216
0
            return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3217
0
        }
3218
3219
        /* Append the signature to ssl->out_msg, leaving 2 bytes for the
3220
         * signature length which will be added in ssl_write_server_key_exchange
3221
         * after the call to ssl_prepare_server_key_exchange.
3222
         * ssl_write_server_key_exchange also takes care of incrementing
3223
         * ssl->out_msglen. */
3224
0
        if ((ret = mbedtls_pk_sign(mbedtls_ssl_own_key(ssl),
3225
0
                                   md_alg, hash, hashlen,
3226
0
                                   ssl->out_msg + ssl->out_msglen + 2,
3227
0
                                   out_buf_len - ssl->out_msglen - 2,
3228
0
                                   signature_len,
3229
0
                                   ssl->conf->f_rng,
3230
0
                                   ssl->conf->p_rng)) != 0) {
3231
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_sign", ret);
3232
0
            return ret;
3233
0
        }
3234
0
    }
3235
124
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3236
3237
124
    return 0;
3238
124
}
3239
3240
/* Prepare the ServerKeyExchange message and send it. For ciphersuites
3241
 * that do not include a ServerKeyExchange message, do nothing. Either
3242
 * way, if successful, move on to the next step in the SSL state
3243
 * machine. */
3244
MBEDTLS_CHECK_RETURN_CRITICAL
3245
static int ssl_write_server_key_exchange(mbedtls_ssl_context *ssl)
3246
202
{
3247
202
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3248
202
    size_t signature_len = 0;
3249
202
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3250
202
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
3251
202
        ssl->handshake->ciphersuite_info;
3252
202
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3253
3254
202
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server key exchange"));
3255
3256
202
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
3257
    /* Extract static ECDH parameters and abort if ServerKeyExchange
3258
     * is not needed. */
3259
202
    if (mbedtls_ssl_ciphersuite_no_pfs(ciphersuite_info)) {
3260
        /* For suites involving ECDH, extract DH parameters
3261
         * from certificate at this point. */
3262
75
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED)
3263
75
        if (mbedtls_ssl_ciphersuite_uses_ecdh(ciphersuite_info)) {
3264
0
            ret = ssl_get_ecdh_params_from_cert(ssl);
3265
0
            if (ret != 0) {
3266
0
                MBEDTLS_SSL_DEBUG_RET(1, "ssl_get_ecdh_params_from_cert", ret);
3267
0
                return ret;
3268
0
            }
3269
0
        }
3270
75
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */
3271
3272
        /* Key exchanges not involving ephemeral keys don't use
3273
         * ServerKeyExchange, so end here. */
3274
75
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write server key exchange"));
3275
75
        ssl->state++;
3276
75
        return 0;
3277
75
    }
3278
127
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
3279
3280
127
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \
3281
127
    defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3282
    /* If we have already prepared the message and there is an ongoing
3283
     * signature operation, resume signing. */
3284
127
    if (ssl->handshake->async_in_progress != 0) {
3285
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("resuming signature operation"));
3286
0
        ret = ssl_resume_server_key_exchange(ssl, &signature_len);
3287
0
    } else
3288
127
#endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) &&
3289
          defined(MBEDTLS_SSL_ASYNC_PRIVATE) */
3290
127
    {
3291
        /* ServerKeyExchange is needed. Prepare the message. */
3292
127
        ret = ssl_prepare_server_key_exchange(ssl, &signature_len);
3293
127
    }
3294
3295
127
    if (ret != 0) {
3296
        /* If we're starting to write a new message, set ssl->out_msglen
3297
         * to 0. But if we're resuming after an asynchronous message,
3298
         * out_msglen is the amount of data written so far and mst be
3299
         * preserved. */
3300
3
        if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3301
0
            MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange (pending)"));
3302
3
        } else {
3303
3
            ssl->out_msglen = 0;
3304
3
        }
3305
3
        return ret;
3306
3
    }
3307
3308
    /* If there is a signature, write its length.
3309
     * ssl_prepare_server_key_exchange already wrote the signature
3310
     * itself at its proper place in the output buffer. */
3311
124
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
3312
124
    if (signature_len != 0) {
3313
0
        ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_1(signature_len);
3314
0
        ssl->out_msg[ssl->out_msglen++] = MBEDTLS_BYTE_0(signature_len);
3315
3316
0
        MBEDTLS_SSL_DEBUG_BUF(3, "my signature",
3317
0
                              ssl->out_msg + ssl->out_msglen,
3318
0
                              signature_len);
3319
3320
        /* Skip over the already-written signature */
3321
0
        ssl->out_msglen += signature_len;
3322
0
    }
3323
124
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
3324
3325
    /* Add header and send. */
3326
124
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3327
124
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE;
3328
3329
124
    ssl->state++;
3330
3331
124
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3332
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3333
0
        return ret;
3334
0
    }
3335
3336
124
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server key exchange"));
3337
124
    return 0;
3338
124
}
3339
3340
MBEDTLS_CHECK_RETURN_CRITICAL
3341
static int ssl_write_server_hello_done(mbedtls_ssl_context *ssl)
3342
199
{
3343
199
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3344
3345
199
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello done"));
3346
3347
199
    ssl->out_msglen  = 4;
3348
199
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3349
199
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_SERVER_HELLO_DONE;
3350
3351
199
    ssl->state++;
3352
3353
199
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3354
199
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3355
0
        mbedtls_ssl_send_flight_completed(ssl);
3356
0
    }
3357
199
#endif
3358
3359
199
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3360
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3361
0
        return ret;
3362
0
    }
3363
3364
199
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3365
199
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3366
199
        (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
3367
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
3368
0
        return ret;
3369
0
    }
3370
199
#endif /* MBEDTLS_SSL_PROTO_DTLS */
3371
3372
199
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello done"));
3373
3374
199
    return 0;
3375
199
}
3376
3377
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) ||                       \
3378
    defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3379
MBEDTLS_CHECK_RETURN_CRITICAL
3380
static int ssl_parse_client_dh_public(mbedtls_ssl_context *ssl, unsigned char **p,
3381
                                      const unsigned char *end)
3382
0
{
3383
0
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3384
0
    size_t n;
3385
3386
    /*
3387
     * Receive G^Y mod P, premaster = (G^Y)^X mod P
3388
     */
3389
0
    if (*p + 2 > end) {
3390
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3391
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3392
0
    }
3393
3394
0
    n = MBEDTLS_GET_UINT16_BE(*p, 0);
3395
0
    *p += 2;
3396
3397
0
    if (*p + n > end) {
3398
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3399
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3400
0
    }
3401
3402
0
    if ((ret = mbedtls_dhm_read_public(&ssl->handshake->dhm_ctx, *p, n)) != 0) {
3403
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_read_public", ret);
3404
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3405
0
    }
3406
3407
0
    *p += n;
3408
3409
0
    MBEDTLS_SSL_DEBUG_MPI(3, "DHM: GY", &ssl->handshake->dhm_ctx.GY);
3410
3411
0
    return ret;
3412
0
}
3413
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED ||
3414
          MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3415
3416
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) ||                           \
3417
    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3418
3419
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3420
MBEDTLS_CHECK_RETURN_CRITICAL
3421
static int ssl_resume_decrypt_pms(mbedtls_ssl_context *ssl,
3422
                                  unsigned char *peer_pms,
3423
                                  size_t *peer_pmslen,
3424
                                  size_t peer_pmssize)
3425
0
{
3426
0
    int ret = ssl->conf->f_async_resume(ssl,
3427
0
                                        peer_pms, peer_pmslen, peer_pmssize);
3428
0
    if (ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3429
0
        ssl->handshake->async_in_progress = 0;
3430
0
        mbedtls_ssl_set_async_operation_data(ssl, NULL);
3431
0
    }
3432
0
    MBEDTLS_SSL_DEBUG_RET(2, "ssl_decrypt_encrypted_pms", ret);
3433
0
    return ret;
3434
0
}
3435
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3436
3437
MBEDTLS_CHECK_RETURN_CRITICAL
3438
static int ssl_decrypt_encrypted_pms(mbedtls_ssl_context *ssl,
3439
                                     const unsigned char *p,
3440
                                     const unsigned char *end,
3441
                                     unsigned char *peer_pms,
3442
                                     size_t *peer_pmslen,
3443
                                     size_t peer_pmssize)
3444
0
{
3445
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3446
3447
0
    mbedtls_x509_crt *own_cert = mbedtls_ssl_own_cert(ssl);
3448
0
    if (own_cert == NULL) {
3449
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no local certificate"));
3450
0
        return MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
3451
0
    }
3452
0
    mbedtls_pk_context *public_key = &own_cert->pk;
3453
0
    mbedtls_pk_context *private_key = mbedtls_ssl_own_key(ssl);
3454
0
    size_t len = mbedtls_pk_get_len(public_key);
3455
3456
0
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3457
    /* If we have already started decoding the message and there is an ongoing
3458
     * decryption operation, resume signing. */
3459
0
    if (ssl->handshake->async_in_progress != 0) {
3460
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("resuming decryption operation"));
3461
0
        return ssl_resume_decrypt_pms(ssl,
3462
0
                                      peer_pms, peer_pmslen, peer_pmssize);
3463
0
    }
3464
0
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3465
3466
    /*
3467
     * Prepare to decrypt the premaster using own private RSA key
3468
     */
3469
0
    if (p + 2 > end) {
3470
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3471
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3472
0
    }
3473
0
    if (*p++ != MBEDTLS_BYTE_1(len) ||
3474
0
        *p++ != MBEDTLS_BYTE_0(len)) {
3475
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3476
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3477
0
    }
3478
3479
0
    if (p + len != end) {
3480
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3481
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3482
0
    }
3483
3484
    /*
3485
     * Decrypt the premaster secret
3486
     */
3487
0
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3488
0
    if (ssl->conf->f_async_decrypt_start != NULL) {
3489
0
        ret = ssl->conf->f_async_decrypt_start(ssl,
3490
0
                                               mbedtls_ssl_own_cert(ssl),
3491
0
                                               p, len);
3492
0
        switch (ret) {
3493
0
            case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH:
3494
                /* act as if f_async_decrypt_start was null */
3495
0
                break;
3496
0
            case 0:
3497
0
                ssl->handshake->async_in_progress = 1;
3498
0
                return ssl_resume_decrypt_pms(ssl,
3499
0
                                              peer_pms,
3500
0
                                              peer_pmslen,
3501
0
                                              peer_pmssize);
3502
0
            case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS:
3503
0
                ssl->handshake->async_in_progress = 1;
3504
0
                return MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS;
3505
0
            default:
3506
0
                MBEDTLS_SSL_DEBUG_RET(1, "f_async_decrypt_start", ret);
3507
0
                return ret;
3508
0
        }
3509
0
    }
3510
0
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3511
3512
0
    if (!mbedtls_pk_can_do(private_key, MBEDTLS_PK_RSA)) {
3513
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no RSA private key"));
3514
0
        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3515
0
    }
3516
3517
0
    ret = mbedtls_pk_decrypt(private_key, p, len,
3518
0
                             peer_pms, peer_pmslen, peer_pmssize,
3519
0
                             ssl->conf->f_rng, ssl->conf->p_rng);
3520
0
    return ret;
3521
0
}
3522
3523
MBEDTLS_CHECK_RETURN_CRITICAL
3524
static int ssl_parse_encrypted_pms(mbedtls_ssl_context *ssl,
3525
                                   const unsigned char *p,
3526
                                   const unsigned char *end,
3527
                                   size_t pms_offset)
3528
0
{
3529
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3530
0
    unsigned char *pms = ssl->handshake->premaster + pms_offset;
3531
0
    unsigned char ver[2];
3532
0
    unsigned char fake_pms[48], peer_pms[48];
3533
0
    size_t peer_pmslen;
3534
0
    mbedtls_ct_condition_t diff;
3535
3536
    /* In case of a failure in decryption, the decryption may write less than
3537
     * 2 bytes of output, but we always read the first two bytes. It doesn't
3538
     * matter in the end because diff will be nonzero in that case due to
3539
     * ret being nonzero, and we only care whether diff is 0.
3540
     * But do initialize peer_pms and peer_pmslen for robustness anyway. This
3541
     * also makes memory analyzers happy (don't access uninitialized memory,
3542
     * even if it's an unsigned char). */
3543
0
    peer_pms[0] = peer_pms[1] = ~0;
3544
0
    peer_pmslen = 0;
3545
3546
0
    ret = ssl_decrypt_encrypted_pms(ssl, p, end,
3547
0
                                    peer_pms,
3548
0
                                    &peer_pmslen,
3549
0
                                    sizeof(peer_pms));
3550
3551
0
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3552
0
    if (ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS) {
3553
0
        return ret;
3554
0
    }
3555
0
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3556
3557
0
    mbedtls_ssl_write_version(ver, ssl->conf->transport,
3558
0
                              ssl->session_negotiate->tls_version);
3559
3560
    /* Avoid data-dependent branches while checking for invalid
3561
     * padding, to protect against timing-based Bleichenbacher-type
3562
     * attacks. */
3563
0
    diff = mbedtls_ct_bool(ret);
3564
0
    diff = mbedtls_ct_bool_or(diff, mbedtls_ct_uint_ne(peer_pmslen, 48));
3565
0
    diff = mbedtls_ct_bool_or(diff, mbedtls_ct_uint_ne(peer_pms[0], ver[0]));
3566
0
    diff = mbedtls_ct_bool_or(diff, mbedtls_ct_uint_ne(peer_pms[1], ver[1]));
3567
3568
    /*
3569
     * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding
3570
     * must not cause the connection to end immediately; instead, send a
3571
     * bad_record_mac later in the handshake.
3572
     * To protect against timing-based variants of the attack, we must
3573
     * not have any branch that depends on whether the decryption was
3574
     * successful. In particular, always generate the fake premaster secret,
3575
     * regardless of whether it will ultimately influence the output or not.
3576
     */
3577
0
    ret = ssl->conf->f_rng(ssl->conf->p_rng, fake_pms, sizeof(fake_pms));
3578
0
    if (ret != 0) {
3579
        /* It's ok to abort on an RNG failure, since this does not reveal
3580
         * anything about the RSA decryption. */
3581
0
        return ret;
3582
0
    }
3583
3584
0
#if defined(MBEDTLS_SSL_DEBUG_ALL)
3585
0
    if (diff != MBEDTLS_CT_FALSE) {
3586
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3587
0
    }
3588
0
#endif
3589
3590
0
    if (sizeof(ssl->handshake->premaster) < pms_offset ||
3591
0
        sizeof(ssl->handshake->premaster) - pms_offset < 48) {
3592
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3593
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3594
0
    }
3595
0
    ssl->handshake->pmslen = 48;
3596
3597
    /* Set pms to either the true or the fake PMS, without
3598
     * data-dependent branches. */
3599
0
    mbedtls_ct_memcpy_if(diff, pms, fake_pms, peer_pms, ssl->handshake->pmslen);
3600
3601
0
    return 0;
3602
0
}
3603
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED ||
3604
          MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
3605
3606
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
3607
MBEDTLS_CHECK_RETURN_CRITICAL
3608
static int ssl_parse_client_psk_identity(mbedtls_ssl_context *ssl, unsigned char **p,
3609
                                         const unsigned char *end)
3610
48
{
3611
48
    int ret = 0;
3612
48
    uint16_t n;
3613
3614
48
    if (ssl_conf_has_psk_or_cb(ssl->conf) == 0) {
3615
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no pre-shared key"));
3616
0
        return MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED;
3617
0
    }
3618
3619
    /*
3620
     * Receive client pre-shared key identity name
3621
     */
3622
48
    if (end - *p < 2) {
3623
4
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3624
4
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3625
4
    }
3626
3627
44
    n = MBEDTLS_GET_UINT16_BE(*p, 0);
3628
44
    *p += 2;
3629
3630
44
    if (n == 0 || n > end - *p) {
3631
20
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3632
20
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
3633
20
    }
3634
3635
24
    if (ssl->conf->f_psk != NULL) {
3636
0
        if (ssl->conf->f_psk(ssl->conf->p_psk, ssl, *p, n) != 0) {
3637
0
            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3638
0
        }
3639
24
    } else {
3640
        /* Identity is not a big secret since clients send it in the clear,
3641
         * but treat it carefully anyway, just in case */
3642
24
        if (n != ssl->conf->psk_identity_len ||
3643
24
            mbedtls_ct_memcmp(ssl->conf->psk_identity, *p, n) != 0) {
3644
24
            ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3645
24
        }
3646
24
    }
3647
3648
24
    if (ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
3649
24
        MBEDTLS_SSL_DEBUG_BUF(3, "Unknown PSK identity", *p, n);
3650
24
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3651
24
                                       MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY);
3652
24
        return MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
3653
24
    }
3654
3655
0
    *p += n;
3656
3657
0
    return 0;
3658
24
}
3659
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
3660
3661
MBEDTLS_CHECK_RETURN_CRITICAL
3662
static int ssl_parse_client_key_exchange(mbedtls_ssl_context *ssl)
3663
199
{
3664
199
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3665
199
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3666
199
    unsigned char *p, *end;
3667
3668
199
    ciphersuite_info = ssl->handshake->ciphersuite_info;
3669
3670
199
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client key exchange"));
3671
3672
199
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
3673
199
    (defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
3674
199
    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED))
3675
199
    if ((ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3676
199
         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) &&
3677
199
        (ssl->handshake->async_in_progress != 0)) {
3678
        /* We've already read a record and there is an asynchronous
3679
         * operation in progress to decrypt it. So skip reading the
3680
         * record. */
3681
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("will resume decryption of previously-read record"));
3682
0
    } else
3683
199
#endif
3684
199
    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3685
121
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3686
121
        return ret;
3687
121
    }
3688
3689
78
    p = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
3690
78
    end = ssl->in_msg + ssl->in_hslen;
3691
3692
78
    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
3693
4
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3694
4
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3695
4
    }
3696
3697
74
    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE) {
3698
26
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3699
26
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3700
26
    }
3701
3702
48
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
3703
48
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA) {
3704
0
        if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
3705
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
3706
0
            return ret;
3707
0
        }
3708
3709
0
        if (p != end) {
3710
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3711
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3712
0
        }
3713
3714
0
        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
3715
0
                                           ssl->handshake->premaster,
3716
0
                                           MBEDTLS_PREMASTER_SIZE,
3717
0
                                           &ssl->handshake->pmslen,
3718
0
                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3719
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
3720
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3721
0
        }
3722
3723
0
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
3724
0
    } else
3725
48
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
3726
48
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
3727
48
    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
3728
48
    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
3729
48
    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
3730
48
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3731
48
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
3732
48
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
3733
48
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA) {
3734
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3735
        size_t data_len = (size_t) (*p++);
3736
        size_t buf_len = (size_t) (end - p);
3737
0
        psa_status_t status = PSA_ERROR_GENERIC_ERROR;
3738
        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3739
3740
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("Read the peer's public key."));
3741
3742
        /*
3743
         * We must have at least two bytes (1 for length, at least 1 for data)
3744
         */
3745
0
        if (buf_len < 2) {
3746
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid buffer length: %" MBEDTLS_PRINTF_SIZET,
3747
0
                                      buf_len));
3748
0
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3749
0
        }
3750
3751
0
        if (data_len < 1 || data_len > buf_len) {
3752
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid data length: %" MBEDTLS_PRINTF_SIZET
3753
0
                                      " > %" MBEDTLS_PRINTF_SIZET,
3754
0
                                      data_len, buf_len));
3755
0
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3756
0
        }
3757
3758
        /* Store peer's ECDH public key. */
3759
0
        if (data_len > sizeof(handshake->xxdh_psa_peerkey)) {
3760
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid public key length: %" MBEDTLS_PRINTF_SIZET
3761
0
                                      " > %" MBEDTLS_PRINTF_SIZET,
3762
0
                                      data_len,
3763
0
                                      sizeof(handshake->xxdh_psa_peerkey)));
3764
0
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3765
0
        }
3766
0
        memcpy(handshake->xxdh_psa_peerkey, p, data_len);
3767
0
        handshake->xxdh_psa_peerkey_len = data_len;
3768
3769
        /* Compute ECDH shared secret. */
3770
0
        status = psa_raw_key_agreement(
3771
0
            PSA_ALG_ECDH, handshake->xxdh_psa_privkey,
3772
0
            handshake->xxdh_psa_peerkey, handshake->xxdh_psa_peerkey_len,
3773
0
            handshake->premaster, sizeof(handshake->premaster),
3774
0
            &handshake->pmslen);
3775
0
        if (status != PSA_SUCCESS) {
3776
0
            ret = PSA_TO_MBEDTLS_ERR(status);
3777
0
            MBEDTLS_SSL_DEBUG_RET(1, "psa_raw_key_agreement", ret);
3778
0
            if (handshake->xxdh_psa_privkey_is_external == 0) {
3779
0
                (void) psa_destroy_key(handshake->xxdh_psa_privkey);
3780
0
            }
3781
0
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3782
0
            return ret;
3783
0
        }
3784
3785
0
        if (handshake->xxdh_psa_privkey_is_external == 0) {
3786
0
            status = psa_destroy_key(handshake->xxdh_psa_privkey);
3787
3788
0
            if (status != PSA_SUCCESS) {
3789
0
                ret = PSA_TO_MBEDTLS_ERR(status);
3790
0
                MBEDTLS_SSL_DEBUG_RET(1, "psa_destroy_key", ret);
3791
0
                return ret;
3792
0
            }
3793
0
        }
3794
0
        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3795
#else
3796
0
        if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
3797
0
                                            p, (size_t) (end - p))) != 0) {
3798
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
3799
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3800
0
        }
3801
3802
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3803
0
                               MBEDTLS_DEBUG_ECDH_QP);
3804
3805
0
        if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx,
3806
0
                                            &ssl->handshake->pmslen,
3807
0
                                            ssl->handshake->premaster,
3808
0
                                            MBEDTLS_MPI_MAX_SIZE,
3809
0
                                            ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3810
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
3811
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3812
0
        }
3813
3814
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3815
0
                               MBEDTLS_DEBUG_ECDH_Z);
3816
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3817
0
    } else
3818
48
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3819
          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
3820
          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
3821
          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3822
48
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
3823
48
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK) {
3824
29
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3825
29
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3826
29
            return ret;
3827
29
        }
3828
3829
0
        if (p != end) {
3830
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3831
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3832
0
        }
3833
3834
#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3835
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3836
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3837
0
                                                    key_exchange)) != 0) {
3838
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3839
0
            return ret;
3840
0
        }
3841
#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3842
0
    } else
3843
19
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
3844
19
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3845
19
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
3846
0
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3847
0
        if (ssl->handshake->async_in_progress != 0) {
3848
            /* There is an asynchronous operation in progress to
3849
             * decrypt the encrypted premaster secret, so skip
3850
             * directly to resuming this operation. */
3851
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("PSK identity already parsed"));
3852
            /* Update p to skip the PSK identity. ssl_parse_encrypted_pms
3853
             * won't actually use it, but maintain p anyway for robustness. */
3854
0
            p += ssl->conf->psk_identity_len + 2;
3855
0
        } else
3856
0
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3857
0
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3858
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3859
0
            return ret;
3860
0
        }
3861
3862
0
        if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 2)) != 0) {
3863
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_encrypted_pms"), ret);
3864
0
            return ret;
3865
0
        }
3866
3867
#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3868
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3869
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3870
0
                                                    key_exchange)) != 0) {
3871
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3872
0
            return ret;
3873
0
        }
3874
#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3875
0
    } else
3876
19
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
3877
19
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3878
19
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
3879
13
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3880
13
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3881
13
            return ret;
3882
13
        }
3883
0
        if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
3884
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
3885
0
            return ret;
3886
0
        }
3887
3888
0
        if (p != end) {
3889
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3890
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3891
0
        }
3892
3893
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3894
0
        unsigned char *pms = ssl->handshake->premaster;
3895
0
        unsigned char *pms_end = pms + sizeof(ssl->handshake->premaster);
3896
0
        size_t pms_len;
3897
3898
        /* Write length only when we know the actual value */
3899
0
        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
3900
0
                                           pms + 2, pms_end - (pms + 2), &pms_len,
3901
0
                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3902
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
3903
0
            return ret;
3904
0
        }
3905
0
        MBEDTLS_PUT_UINT16_BE(pms_len, pms, 0);
3906
0
        pms += 2 + pms_len;
3907
3908
0
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
3909
#else
3910
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3911
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3912
0
                                                    key_exchange)) != 0) {
3913
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3914
0
            return ret;
3915
0
        }
3916
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3917
0
    } else
3918
6
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3919
6
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3920
6
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
3921
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3922
0
        psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3923
0
        psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
3924
        uint8_t ecpoint_len;
3925
3926
        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3927
3928
0
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3929
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3930
0
            psa_destroy_key(handshake->xxdh_psa_privkey);
3931
0
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3932
0
            return ret;
3933
0
        }
3934
3935
        /* Keep a copy of the peer's public key */
3936
0
        if (p >= end) {
3937
0
            psa_destroy_key(handshake->xxdh_psa_privkey);
3938
0
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3939
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3940
0
        }
3941
3942
0
        ecpoint_len = *(p++);
3943
0
        if ((size_t) (end - p) < ecpoint_len) {
3944
0
            psa_destroy_key(handshake->xxdh_psa_privkey);
3945
0
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3946
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3947
0
        }
3948
3949
        /* When FFDH is enabled, the array handshake->xxdh_psa_peer_key size takes into account
3950
           the sizes of the FFDH keys which are at least 2048 bits.
3951
           The size of the array is thus greater than 256 bytes which is greater than any
3952
           possible value of ecpoint_len (type uint8_t) and the check below can be skipped.*/
3953
#if !defined(PSA_WANT_ALG_FFDH)
3954
        if (ecpoint_len > sizeof(handshake->xxdh_psa_peerkey)) {
3955
            psa_destroy_key(handshake->xxdh_psa_privkey);
3956
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3957
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3958
        }
3959
#else
3960
0
        MBEDTLS_STATIC_ASSERT(sizeof(handshake->xxdh_psa_peerkey) >= UINT8_MAX,
3961
0
                              "peer key buffer too small");
3962
0
#endif
3963
3964
        memcpy(handshake->xxdh_psa_peerkey, p, ecpoint_len);
3965
        handshake->xxdh_psa_peerkey_len = ecpoint_len;
3966
        p += ecpoint_len;
3967
3968
        /* As RFC 5489 section 2, the premaster secret is formed as follows:
3969
         * - a uint16 containing the length (in octets) of the ECDH computation
3970
         * - the octet string produced by the ECDH computation
3971
         * - a uint16 containing the length (in octets) of the PSK
3972
         * - the PSK itself
3973
         */
3974
        unsigned char *psm = ssl->handshake->premaster;
3975
        const unsigned char * const psm_end =
3976
            psm + sizeof(ssl->handshake->premaster);
3977
        /* uint16 to store length (in octets) of the ECDH computation */
3978
        const size_t zlen_size = 2;
3979
        size_t zlen = 0;
3980
3981
        /* Compute ECDH shared secret. */
3982
0
        status = psa_raw_key_agreement(PSA_ALG_ECDH,
3983
                                       handshake->xxdh_psa_privkey,
3984
                                       handshake->xxdh_psa_peerkey,
3985
                                       handshake->xxdh_psa_peerkey_len,
3986
                                       psm + zlen_size,
3987
                                       psm_end - (psm + zlen_size),
3988
                                       &zlen);
3989
3990
        destruction_status = psa_destroy_key(handshake->xxdh_psa_privkey);
3991
0
        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3992
3993
0
        if (status != PSA_SUCCESS) {
3994
0
            return PSA_TO_MBEDTLS_ERR(status);
3995
0
        } else if (destruction_status != PSA_SUCCESS) {
3996
0
            return PSA_TO_MBEDTLS_ERR(destruction_status);
3997
0
        }
3998
3999
        /* Write the ECDH computation length before the ECDH computation */
4000
0
        MBEDTLS_PUT_UINT16_BE(zlen, psm, 0);
4001
0
        psm += zlen_size + zlen;
4002
4003
#else /* MBEDTLS_USE_PSA_CRYPTO */
4004
6
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
4005
6
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
4006
6
            return ret;
4007
6
        }
4008
4009
0
        if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
4010
0
                                            p, (size_t) (end - p))) != 0) {
4011
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
4012
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
4013
0
        }
4014
4015
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
4016
0
                               MBEDTLS_DEBUG_ECDH_QP);
4017
4018
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
4019
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
4020
0
                                                    key_exchange)) != 0) {
4021
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
4022
0
            return ret;
4023
0
        }
4024
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4025
0
    } else
4026
0
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
4027
0
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
4028
0
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) {
4029
0
        if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 0)) != 0) {
4030
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_parse_encrypted_pms_secret"), ret);
4031
0
            return ret;
4032
0
        }
4033
0
    } else
4034
0
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
4035
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4036
0
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
4037
#if defined(MBEDTLS_USE_PSA_CRYPTO)
4038
0
        if ((ret = mbedtls_psa_ecjpake_read_round(
4039
0
                 &ssl->handshake->psa_pake_ctx, p, (size_t) (end - p),
4040
0
                 MBEDTLS_ECJPAKE_ROUND_TWO)) != 0) {
4041
0
            psa_destroy_key(ssl->handshake->psa_pake_password);
4042
0
            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
4043
4044
0
            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_input round two", ret);
4045
0
            return ret;
4046
0
        }
4047
#else
4048
        ret = mbedtls_ecjpake_read_round_two(&ssl->handshake->ecjpake_ctx,
4049
                                             p, (size_t) (end - p));
4050
0
        if (ret != 0) {
4051
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_two", ret);
4052
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4053
0
        }
4054
4055
0
        ret = mbedtls_ecjpake_derive_secret(&ssl->handshake->ecjpake_ctx,
4056
0
                                            ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
4057
0
                                            ssl->conf->f_rng, ssl->conf->p_rng);
4058
0
        if (ret != 0) {
4059
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_derive_secret", ret);
4060
0
            return ret;
4061
0
        }
4062
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4063
0
    } else
4064
0
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4065
0
    {
4066
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4067
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4068
0
    }
4069
4070
0
    if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
4071
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
4072
0
        return ret;
4073
0
    }
4074
4075
0
    ssl->state++;
4076
4077
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client key exchange"));
4078
4079
0
    return 0;
4080
0
}
ssl_tls12_server.c:ssl_parse_client_key_exchange
Line
Count
Source
3663
199
{
3664
199
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3665
199
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3666
199
    unsigned char *p, *end;
3667
3668
199
    ciphersuite_info = ssl->handshake->ciphersuite_info;
3669
3670
199
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client key exchange"));
3671
3672
199
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \
3673
199
    (defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
3674
199
    defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED))
3675
199
    if ((ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ||
3676
199
         ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) &&
3677
199
        (ssl->handshake->async_in_progress != 0)) {
3678
        /* We've already read a record and there is an asynchronous
3679
         * operation in progress to decrypt it. So skip reading the
3680
         * record. */
3681
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("will resume decryption of previously-read record"));
3682
0
    } else
3683
199
#endif
3684
199
    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3685
121
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3686
121
        return ret;
3687
121
    }
3688
3689
78
    p = ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl);
3690
78
    end = ssl->in_msg + ssl->in_hslen;
3691
3692
78
    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
3693
4
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3694
4
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3695
4
    }
3696
3697
74
    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE) {
3698
26
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange message"));
3699
26
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3700
26
    }
3701
3702
48
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
3703
48
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA) {
3704
0
        if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
3705
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
3706
0
            return ret;
3707
0
        }
3708
3709
0
        if (p != end) {
3710
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3711
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3712
0
        }
3713
3714
0
        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
3715
0
                                           ssl->handshake->premaster,
3716
0
                                           MBEDTLS_PREMASTER_SIZE,
3717
0
                                           &ssl->handshake->pmslen,
3718
0
                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3719
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
3720
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3721
0
        }
3722
3723
0
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
3724
0
    } else
3725
48
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */
3726
48
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) ||                     \
3727
48
    defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) ||                   \
3728
48
    defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) ||                      \
3729
48
    defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
3730
48
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA ||
3731
48
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ||
3732
48
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA ||
3733
48
        ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA) {
3734
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3735
        size_t data_len = (size_t) (*p++);
3736
        size_t buf_len = (size_t) (end - p);
3737
        psa_status_t status = PSA_ERROR_GENERIC_ERROR;
3738
        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3739
3740
        MBEDTLS_SSL_DEBUG_MSG(3, ("Read the peer's public key."));
3741
3742
        /*
3743
         * We must have at least two bytes (1 for length, at least 1 for data)
3744
         */
3745
        if (buf_len < 2) {
3746
            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid buffer length: %" MBEDTLS_PRINTF_SIZET,
3747
                                      buf_len));
3748
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3749
        }
3750
3751
        if (data_len < 1 || data_len > buf_len) {
3752
            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid data length: %" MBEDTLS_PRINTF_SIZET
3753
                                      " > %" MBEDTLS_PRINTF_SIZET,
3754
                                      data_len, buf_len));
3755
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3756
        }
3757
3758
        /* Store peer's ECDH public key. */
3759
        if (data_len > sizeof(handshake->xxdh_psa_peerkey)) {
3760
            MBEDTLS_SSL_DEBUG_MSG(1, ("Invalid public key length: %" MBEDTLS_PRINTF_SIZET
3761
                                      " > %" MBEDTLS_PRINTF_SIZET,
3762
                                      data_len,
3763
                                      sizeof(handshake->xxdh_psa_peerkey)));
3764
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3765
        }
3766
        memcpy(handshake->xxdh_psa_peerkey, p, data_len);
3767
        handshake->xxdh_psa_peerkey_len = data_len;
3768
3769
        /* Compute ECDH shared secret. */
3770
        status = psa_raw_key_agreement(
3771
            PSA_ALG_ECDH, handshake->xxdh_psa_privkey,
3772
            handshake->xxdh_psa_peerkey, handshake->xxdh_psa_peerkey_len,
3773
            handshake->premaster, sizeof(handshake->premaster),
3774
            &handshake->pmslen);
3775
        if (status != PSA_SUCCESS) {
3776
            ret = PSA_TO_MBEDTLS_ERR(status);
3777
            MBEDTLS_SSL_DEBUG_RET(1, "psa_raw_key_agreement", ret);
3778
            if (handshake->xxdh_psa_privkey_is_external == 0) {
3779
                (void) psa_destroy_key(handshake->xxdh_psa_privkey);
3780
            }
3781
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3782
            return ret;
3783
        }
3784
3785
        if (handshake->xxdh_psa_privkey_is_external == 0) {
3786
            status = psa_destroy_key(handshake->xxdh_psa_privkey);
3787
3788
            if (status != PSA_SUCCESS) {
3789
                ret = PSA_TO_MBEDTLS_ERR(status);
3790
                MBEDTLS_SSL_DEBUG_RET(1, "psa_destroy_key", ret);
3791
                return ret;
3792
            }
3793
        }
3794
        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3795
#else
3796
0
        if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
3797
0
                                            p, (size_t) (end - p))) != 0) {
3798
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
3799
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3800
0
        }
3801
3802
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3803
0
                               MBEDTLS_DEBUG_ECDH_QP);
3804
3805
0
        if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx,
3806
0
                                            &ssl->handshake->pmslen,
3807
0
                                            ssl->handshake->premaster,
3808
0
                                            MBEDTLS_MPI_MAX_SIZE,
3809
0
                                            ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3810
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
3811
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3812
0
        }
3813
3814
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
3815
0
                               MBEDTLS_DEBUG_ECDH_Z);
3816
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3817
0
    } else
3818
48
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED ||
3819
          MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED ||
3820
          MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED ||
3821
          MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */
3822
48
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
3823
48
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK) {
3824
29
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3825
29
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3826
29
            return ret;
3827
29
        }
3828
3829
0
        if (p != end) {
3830
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3831
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3832
0
        }
3833
3834
0
#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3835
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3836
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3837
0
                                                    key_exchange)) != 0) {
3838
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3839
0
            return ret;
3840
0
        }
3841
0
#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3842
0
    } else
3843
19
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
3844
19
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
3845
19
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
3846
0
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
3847
0
        if (ssl->handshake->async_in_progress != 0) {
3848
            /* There is an asynchronous operation in progress to
3849
             * decrypt the encrypted premaster secret, so skip
3850
             * directly to resuming this operation. */
3851
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("PSK identity already parsed"));
3852
            /* Update p to skip the PSK identity. ssl_parse_encrypted_pms
3853
             * won't actually use it, but maintain p anyway for robustness. */
3854
0
            p += ssl->conf->psk_identity_len + 2;
3855
0
        } else
3856
0
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
3857
0
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3858
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3859
0
            return ret;
3860
0
        }
3861
3862
0
        if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 2)) != 0) {
3863
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_encrypted_pms"), ret);
3864
0
            return ret;
3865
0
        }
3866
3867
0
#if !defined(MBEDTLS_USE_PSA_CRYPTO)
3868
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3869
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3870
0
                                                    key_exchange)) != 0) {
3871
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3872
0
            return ret;
3873
0
        }
3874
0
#endif /* !MBEDTLS_USE_PSA_CRYPTO */
3875
0
    } else
3876
19
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
3877
19
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
3878
19
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
3879
13
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3880
13
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3881
13
            return ret;
3882
13
        }
3883
0
        if ((ret = ssl_parse_client_dh_public(ssl, &p, end)) != 0) {
3884
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_dh_public"), ret);
3885
0
            return ret;
3886
0
        }
3887
3888
0
        if (p != end) {
3889
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad client key exchange"));
3890
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3891
0
        }
3892
3893
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3894
        unsigned char *pms = ssl->handshake->premaster;
3895
        unsigned char *pms_end = pms + sizeof(ssl->handshake->premaster);
3896
        size_t pms_len;
3897
3898
        /* Write length only when we know the actual value */
3899
        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
3900
                                           pms + 2, pms_end - (pms + 2), &pms_len,
3901
                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
3902
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
3903
            return ret;
3904
        }
3905
        MBEDTLS_PUT_UINT16_BE(pms_len, pms, 0);
3906
        pms += 2 + pms_len;
3907
3908
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
3909
#else
3910
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
3911
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
3912
0
                                                    key_exchange)) != 0) {
3913
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
3914
0
            return ret;
3915
0
        }
3916
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3917
0
    } else
3918
6
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
3919
6
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
3920
6
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
3921
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3922
        psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
3923
        psa_status_t destruction_status = PSA_ERROR_CORRUPTION_DETECTED;
3924
        uint8_t ecpoint_len;
3925
3926
        mbedtls_ssl_handshake_params *handshake = ssl->handshake;
3927
3928
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
3929
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
3930
            psa_destroy_key(handshake->xxdh_psa_privkey);
3931
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3932
            return ret;
3933
        }
3934
3935
        /* Keep a copy of the peer's public key */
3936
        if (p >= end) {
3937
            psa_destroy_key(handshake->xxdh_psa_privkey);
3938
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3939
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3940
        }
3941
3942
        ecpoint_len = *(p++);
3943
        if ((size_t) (end - p) < ecpoint_len) {
3944
            psa_destroy_key(handshake->xxdh_psa_privkey);
3945
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3946
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
3947
        }
3948
3949
        /* When FFDH is enabled, the array handshake->xxdh_psa_peer_key size takes into account
3950
           the sizes of the FFDH keys which are at least 2048 bits.
3951
           The size of the array is thus greater than 256 bytes which is greater than any
3952
           possible value of ecpoint_len (type uint8_t) and the check below can be skipped.*/
3953
#if !defined(PSA_WANT_ALG_FFDH)
3954
        if (ecpoint_len > sizeof(handshake->xxdh_psa_peerkey)) {
3955
            psa_destroy_key(handshake->xxdh_psa_privkey);
3956
            handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3957
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
3958
        }
3959
#else
3960
        MBEDTLS_STATIC_ASSERT(sizeof(handshake->xxdh_psa_peerkey) >= UINT8_MAX,
3961
                              "peer key buffer too small");
3962
#endif
3963
3964
        memcpy(handshake->xxdh_psa_peerkey, p, ecpoint_len);
3965
        handshake->xxdh_psa_peerkey_len = ecpoint_len;
3966
        p += ecpoint_len;
3967
3968
        /* As RFC 5489 section 2, the premaster secret is formed as follows:
3969
         * - a uint16 containing the length (in octets) of the ECDH computation
3970
         * - the octet string produced by the ECDH computation
3971
         * - a uint16 containing the length (in octets) of the PSK
3972
         * - the PSK itself
3973
         */
3974
        unsigned char *psm = ssl->handshake->premaster;
3975
        const unsigned char * const psm_end =
3976
            psm + sizeof(ssl->handshake->premaster);
3977
        /* uint16 to store length (in octets) of the ECDH computation */
3978
        const size_t zlen_size = 2;
3979
        size_t zlen = 0;
3980
3981
        /* Compute ECDH shared secret. */
3982
        status = psa_raw_key_agreement(PSA_ALG_ECDH,
3983
                                       handshake->xxdh_psa_privkey,
3984
                                       handshake->xxdh_psa_peerkey,
3985
                                       handshake->xxdh_psa_peerkey_len,
3986
                                       psm + zlen_size,
3987
                                       psm_end - (psm + zlen_size),
3988
                                       &zlen);
3989
3990
        destruction_status = psa_destroy_key(handshake->xxdh_psa_privkey);
3991
        handshake->xxdh_psa_privkey = MBEDTLS_SVC_KEY_ID_INIT;
3992
3993
        if (status != PSA_SUCCESS) {
3994
            return PSA_TO_MBEDTLS_ERR(status);
3995
        } else if (destruction_status != PSA_SUCCESS) {
3996
            return PSA_TO_MBEDTLS_ERR(destruction_status);
3997
        }
3998
3999
        /* Write the ECDH computation length before the ECDH computation */
4000
        MBEDTLS_PUT_UINT16_BE(zlen, psm, 0);
4001
        psm += zlen_size + zlen;
4002
4003
#else /* MBEDTLS_USE_PSA_CRYPTO */
4004
6
        if ((ret = ssl_parse_client_psk_identity(ssl, &p, end)) != 0) {
4005
6
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_client_psk_identity"), ret);
4006
6
            return ret;
4007
6
        }
4008
4009
0
        if ((ret = mbedtls_ecdh_read_public(&ssl->handshake->ecdh_ctx,
4010
0
                                            p, (size_t) (end - p))) != 0) {
4011
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_read_public", ret);
4012
0
            return MBEDTLS_ERR_SSL_DECODE_ERROR;
4013
0
        }
4014
4015
0
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
4016
0
                               MBEDTLS_DEBUG_ECDH_QP);
4017
4018
0
        if ((ret = mbedtls_ssl_psk_derive_premaster(ssl,
4019
0
                                                    (mbedtls_key_exchange_type_t) ciphersuite_info->
4020
0
                                                    key_exchange)) != 0) {
4021
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_psk_derive_premaster", ret);
4022
0
            return ret;
4023
0
        }
4024
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4025
0
    } else
4026
0
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
4027
0
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
4028
0
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA) {
4029
0
        if ((ret = ssl_parse_encrypted_pms(ssl, p, end, 0)) != 0) {
4030
0
            MBEDTLS_SSL_DEBUG_RET(1, ("ssl_parse_parse_encrypted_pms_secret"), ret);
4031
0
            return ret;
4032
0
        }
4033
0
    } else
4034
0
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */
4035
0
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4036
0
    if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE) {
4037
#if defined(MBEDTLS_USE_PSA_CRYPTO)
4038
        if ((ret = mbedtls_psa_ecjpake_read_round(
4039
                 &ssl->handshake->psa_pake_ctx, p, (size_t) (end - p),
4040
                 MBEDTLS_ECJPAKE_ROUND_TWO)) != 0) {
4041
            psa_destroy_key(ssl->handshake->psa_pake_password);
4042
            psa_pake_abort(&ssl->handshake->psa_pake_ctx);
4043
4044
            MBEDTLS_SSL_DEBUG_RET(1, "psa_pake_input round two", ret);
4045
            return ret;
4046
        }
4047
#else
4048
0
        ret = mbedtls_ecjpake_read_round_two(&ssl->handshake->ecjpake_ctx,
4049
0
                                             p, (size_t) (end - p));
4050
0
        if (ret != 0) {
4051
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_read_round_two", ret);
4052
0
            return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4053
0
        }
4054
4055
0
        ret = mbedtls_ecjpake_derive_secret(&ssl->handshake->ecjpake_ctx,
4056
0
                                            ssl->handshake->premaster, 32, &ssl->handshake->pmslen,
4057
0
                                            ssl->conf->f_rng, ssl->conf->p_rng);
4058
0
        if (ret != 0) {
4059
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecjpake_derive_secret", ret);
4060
0
            return ret;
4061
0
        }
4062
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4063
0
    } else
4064
0
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4065
0
    {
4066
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4067
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4068
0
    }
4069
4070
0
    if ((ret = mbedtls_ssl_derive_keys(ssl)) != 0) {
4071
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_derive_keys", ret);
4072
0
        return ret;
4073
0
    }
4074
4075
0
    ssl->state++;
4076
4077
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client key exchange"));
4078
4079
0
    return 0;
4080
0
}
Unexecuted instantiation: ssl_tls12_server.c:ssl_parse_client_key_exchange
4081
4082
#if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
4083
MBEDTLS_CHECK_RETURN_CRITICAL
4084
static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl)
4085
{
4086
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4087
        ssl->handshake->ciphersuite_info;
4088
4089
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate verify"));
4090
4091
    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
4092
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4093
        ssl->state++;
4094
        return 0;
4095
    }
4096
4097
    MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
4098
    return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4099
}
4100
#else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4101
MBEDTLS_CHECK_RETURN_CRITICAL
4102
static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl)
4103
0
{
4104
0
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4105
0
    size_t i, sig_len;
4106
0
    unsigned char hash[48];
4107
0
    unsigned char *hash_start = hash;
4108
0
    size_t hashlen;
4109
0
    mbedtls_pk_type_t pk_alg;
4110
0
    mbedtls_md_type_t md_alg;
4111
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
4112
0
        ssl->handshake->ciphersuite_info;
4113
0
    mbedtls_pk_context *peer_pk;
4114
4115
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate verify"));
4116
4117
0
    if (!mbedtls_ssl_ciphersuite_cert_req_allowed(ciphersuite_info)) {
4118
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4119
0
        ssl->state++;
4120
0
        return 0;
4121
0
    }
4122
4123
0
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4124
0
    if (ssl->session_negotiate->peer_cert == NULL) {
4125
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4126
0
        ssl->state++;
4127
0
        return 0;
4128
0
    }
4129
#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4130
    if (ssl->session_negotiate->peer_cert_digest == NULL) {
4131
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate verify"));
4132
        ssl->state++;
4133
        return 0;
4134
    }
4135
#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4136
4137
    /* Read the message without adding it to the checksum */
4138
0
    ret = mbedtls_ssl_read_record(ssl, 0 /* no checksum update */);
4139
0
    if (0 != ret) {
4140
0
        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_read_record"), ret);
4141
0
        return ret;
4142
0
    }
4143
4144
0
    ssl->state++;
4145
4146
    /* Process the message contents */
4147
0
    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ||
4148
0
        ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY) {
4149
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4150
0
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
4151
0
    }
4152
4153
0
    i = mbedtls_ssl_hs_hdr_len(ssl);
4154
4155
#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
4156
    peer_pk = &ssl->handshake->peer_pubkey;
4157
#else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4158
0
    if (ssl->session_negotiate->peer_cert == NULL) {
4159
        /* Should never happen */
4160
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
4161
0
    }
4162
0
    peer_pk = &ssl->session_negotiate->peer_cert->pk;
4163
0
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
4164
4165
    /*
4166
     *  struct {
4167
     *     SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only
4168
     *     opaque signature<0..2^16-1>;
4169
     *  } DigitallySigned;
4170
     */
4171
0
    if (i + 2 > ssl->in_hslen) {
4172
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4173
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4174
0
    }
4175
4176
    /*
4177
     * Hash
4178
     */
4179
0
    md_alg = mbedtls_ssl_md_alg_from_hash(ssl->in_msg[i]);
4180
4181
0
    if (md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md(ssl, ssl->in_msg[i])) {
4182
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4183
0
                                  " for verify message"));
4184
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4185
0
    }
4186
4187
0
#if !defined(MBEDTLS_MD_SHA1)
4188
0
    if (MBEDTLS_MD_SHA1 == md_alg) {
4189
0
        hash_start += 16;
4190
0
    }
4191
0
#endif
4192
4193
    /* Info from md_alg will be used instead */
4194
0
    hashlen = 0;
4195
4196
0
    i++;
4197
4198
    /*
4199
     * Signature
4200
     */
4201
0
    if ((pk_alg = mbedtls_ssl_pk_alg_from_sig(ssl->in_msg[i]))
4202
0
        == MBEDTLS_PK_NONE) {
4203
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("peer not adhering to requested sig_alg"
4204
0
                                  " for verify message"));
4205
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4206
0
    }
4207
4208
    /*
4209
     * Check the certificate's key type matches the signature alg
4210
     */
4211
0
    if (!mbedtls_pk_can_do(peer_pk, pk_alg)) {
4212
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("sig_alg doesn't match cert key"));
4213
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
4214
0
    }
4215
4216
0
    i++;
4217
4218
0
    if (i + 2 > ssl->in_hslen) {
4219
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4220
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4221
0
    }
4222
4223
0
    sig_len = MBEDTLS_GET_UINT16_BE(ssl->in_msg, i);
4224
0
    i += 2;
4225
4226
0
    if (i + sig_len != ssl->in_hslen) {
4227
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate verify message"));
4228
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
4229
0
    }
4230
4231
    /* Calculate hash and verify signature */
4232
0
    {
4233
0
        size_t dummy_hlen;
4234
0
        ret = ssl->handshake->calc_verify(ssl, hash, &dummy_hlen);
4235
0
        if (0 != ret) {
4236
0
            MBEDTLS_SSL_DEBUG_RET(1, ("calc_verify"), ret);
4237
0
            return ret;
4238
0
        }
4239
0
    }
4240
4241
0
    if ((ret = mbedtls_pk_verify(peer_pk,
4242
0
                                 md_alg, hash_start, hashlen,
4243
0
                                 ssl->in_msg + i, sig_len)) != 0) {
4244
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_pk_verify", ret);
4245
0
        return ret;
4246
0
    }
4247
4248
0
    ret = mbedtls_ssl_update_handshake_status(ssl);
4249
0
    if (0 != ret) {
4250
0
        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_update_handshake_status"), ret);
4251
0
        return ret;
4252
0
    }
4253
4254
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate verify"));
4255
4256
0
    return ret;
4257
0
}
4258
#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
4259
4260
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
4261
MBEDTLS_CHECK_RETURN_CRITICAL
4262
static int ssl_write_new_session_ticket(mbedtls_ssl_context *ssl)
4263
0
{
4264
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4265
0
    size_t tlen;
4266
0
    uint32_t lifetime;
4267
4268
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write new session ticket"));
4269
4270
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
4271
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_NEW_SESSION_TICKET;
4272
4273
    /*
4274
     * struct {
4275
     *     uint32 ticket_lifetime_hint;
4276
     *     opaque ticket<0..2^16-1>;
4277
     * } NewSessionTicket;
4278
     *
4279
     * 4  .  7   ticket_lifetime_hint (0 = unspecified)
4280
     * 8  .  9   ticket_len (n)
4281
     * 10 .  9+n ticket content
4282
     */
4283
4284
0
#if defined(MBEDTLS_HAVE_TIME)
4285
0
    ssl->session_negotiate->ticket_creation_time = mbedtls_ms_time();
4286
0
#endif
4287
0
    if ((ret = ssl->conf->f_ticket_write(ssl->conf->p_ticket,
4288
0
                                         ssl->session_negotiate,
4289
0
                                         ssl->out_msg + 10,
4290
0
                                         ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN,
4291
0
                                         &tlen, &lifetime)) != 0) {
4292
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_ticket_write", ret);
4293
0
        tlen = 0;
4294
0
    }
4295
4296
0
    MBEDTLS_PUT_UINT32_BE(lifetime, ssl->out_msg, 4);
4297
0
    MBEDTLS_PUT_UINT16_BE(tlen, ssl->out_msg, 8);
4298
0
    ssl->out_msglen = 10 + tlen;
4299
4300
    /*
4301
     * Morally equivalent to updating ssl->state, but NewSessionTicket and
4302
     * ChangeCipherSpec share the same state.
4303
     */
4304
0
    ssl->handshake->new_session_ticket = 0;
4305
4306
0
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
4307
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
4308
0
        return ret;
4309
0
    }
4310
4311
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write new session ticket"));
4312
4313
0
    return 0;
4314
0
}
4315
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
4316
4317
/*
4318
 * SSL handshake -- server side -- single step
4319
 */
4320
int mbedtls_ssl_handshake_server_step(mbedtls_ssl_context *ssl)
4321
4.50k
{
4322
4.50k
    int ret = 0;
4323
4324
4.50k
    MBEDTLS_SSL_DEBUG_MSG(2, ("server state: %d", ssl->state));
4325
4326
4.50k
    switch (ssl->state) {
4327
1.11k
        case MBEDTLS_SSL_HELLO_REQUEST:
4328
1.11k
            ssl->state = MBEDTLS_SSL_CLIENT_HELLO;
4329
1.11k
            break;
4330
4331
        /*
4332
         *  <==   ClientHello
4333
         */
4334
1.98k
        case MBEDTLS_SSL_CLIENT_HELLO:
4335
1.98k
            ret = ssl_parse_client_hello(ssl);
4336
1.98k
            break;
4337
4338
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
4339
0
        case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT:
4340
0
            return MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED;
4341
0
#endif
4342
4343
        /*
4344
         *  ==>   ServerHello
4345
         *        Certificate
4346
         *      ( ServerKeyExchange  )
4347
         *      ( CertificateRequest )
4348
         *        ServerHelloDone
4349
         */
4350
202
        case MBEDTLS_SSL_SERVER_HELLO:
4351
202
            ret = ssl_write_server_hello(ssl);
4352
202
            break;
4353
4354
202
        case MBEDTLS_SSL_SERVER_CERTIFICATE:
4355
202
            ret = mbedtls_ssl_write_certificate(ssl);
4356
202
            break;
4357
4358
202
        case MBEDTLS_SSL_SERVER_KEY_EXCHANGE:
4359
202
            ret = ssl_write_server_key_exchange(ssl);
4360
202
            break;
4361
4362
199
        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
4363
199
            ret = ssl_write_certificate_request(ssl);
4364
199
            break;
4365
4366
199
        case MBEDTLS_SSL_SERVER_HELLO_DONE:
4367
199
            ret = ssl_write_server_hello_done(ssl);
4368
199
            break;
4369
4370
        /*
4371
         *  <== ( Certificate/Alert  )
4372
         *        ClientKeyExchange
4373
         *      ( CertificateVerify  )
4374
         *        ChangeCipherSpec
4375
         *        Finished
4376
         */
4377
199
        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
4378
199
            ret = mbedtls_ssl_parse_certificate(ssl);
4379
199
            break;
4380
4381
199
        case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE:
4382
199
            ret = ssl_parse_client_key_exchange(ssl);
4383
199
            break;
4384
4385
0
        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
4386
0
            ret = ssl_parse_certificate_verify(ssl);
4387
0
            break;
4388
4389
0
        case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC:
4390
0
            ret = mbedtls_ssl_parse_change_cipher_spec(ssl);
4391
0
            break;
4392
4393
0
        case MBEDTLS_SSL_CLIENT_FINISHED:
4394
0
            ret = mbedtls_ssl_parse_finished(ssl);
4395
0
            break;
4396
4397
        /*
4398
         *  ==> ( NewSessionTicket )
4399
         *        ChangeCipherSpec
4400
         *        Finished
4401
         */
4402
0
        case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC:
4403
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
4404
0
            if (ssl->handshake->new_session_ticket != 0) {
4405
0
                ret = ssl_write_new_session_ticket(ssl);
4406
0
            } else
4407
0
#endif
4408
0
            ret = mbedtls_ssl_write_change_cipher_spec(ssl);
4409
0
            break;
4410
4411
0
        case MBEDTLS_SSL_SERVER_FINISHED:
4412
0
            ret = mbedtls_ssl_write_finished(ssl);
4413
0
            break;
4414
4415
0
        case MBEDTLS_SSL_FLUSH_BUFFERS:
4416
0
            MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
4417
0
            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
4418
0
            break;
4419
4420
0
        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
4421
0
            mbedtls_ssl_handshake_wrapup(ssl);
4422
0
            break;
4423
4424
0
        default:
4425
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
4426
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4427
4.50k
    }
4428
4429
4.50k
    return ret;
4430
4.50k
}
4431
4432
void mbedtls_ssl_conf_preference_order(mbedtls_ssl_config *conf, int order)
4433
0
{
4434
0
    conf->respect_cli_pref = order;
4435
0
}
4436
4437
#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_PROTO_TLS1_2 */