Coverage Report

Created: 2026-05-12 06:58

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/mbedtls/library/ssl_tls13_server.c
Line
Count
Source
1
/*
2
 *  TLS 1.3 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_3)
11
12
#include "debug_internal.h"
13
#include "mbedtls/error.h"
14
#include "mbedtls/platform.h"
15
#include "mbedtls/constant_time.h"
16
#include "mbedtls/oid.h"
17
#include "mbedtls/psa_util.h"
18
19
#include "ssl_misc.h"
20
#include "ssl_tls13_keys.h"
21
#include "ssl_debug_helpers.h"
22
23
24
static const mbedtls_ssl_ciphersuite_t *ssl_tls13_validate_peer_ciphersuite(
25
    mbedtls_ssl_context *ssl,
26
    unsigned int cipher_suite)
27
0
{
28
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
29
0
    if (!mbedtls_ssl_tls13_cipher_suite_is_offered(ssl, cipher_suite)) {
30
0
        return NULL;
31
0
    }
32
33
0
    ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(cipher_suite);
34
0
    if ((mbedtls_ssl_validate_ciphersuite(ssl, ciphersuite_info,
35
0
                                          ssl->tls_version,
36
0
                                          ssl->tls_version) != 0)) {
37
0
        return NULL;
38
0
    }
39
0
    return ciphersuite_info;
40
0
}
41
42
static void ssl_tls13_select_ciphersuite(
43
    mbedtls_ssl_context *ssl,
44
    const unsigned char *cipher_suites,
45
    const unsigned char *cipher_suites_end,
46
    int psk_ciphersuite_id,
47
    psa_algorithm_t psk_hash_alg,
48
    const mbedtls_ssl_ciphersuite_t **selected_ciphersuite_info)
49
0
{
50
0
    *selected_ciphersuite_info = NULL;
51
52
    /*
53
     * In a compliant ClientHello the byte-length of the list of ciphersuites
54
     * is even and this function relies on this fact. This should have been
55
     * checked in the main ClientHello parsing function. Double check here.
56
     */
57
0
    if ((cipher_suites_end - cipher_suites) & 1) {
58
0
        return;
59
0
    }
60
61
0
    for (const unsigned char *p = cipher_suites;
62
0
         p < cipher_suites_end; p += 2) {
63
        /*
64
         * "cipher_suites_end - p is even" is an invariant of the loop. As
65
         * cipher_suites_end - p > 0, we have cipher_suites_end - p >= 2 and it
66
         * is thus safe to read two bytes.
67
         */
68
0
        uint16_t id = MBEDTLS_GET_UINT16_BE(p, 0);
69
70
0
        const mbedtls_ssl_ciphersuite_t *info =
71
0
            ssl_tls13_validate_peer_ciphersuite(ssl, id);
72
0
        if (info == NULL) {
73
0
            continue;
74
0
        }
75
76
        /*
77
         * If a valid PSK ciphersuite identifier has been passed in, we want
78
         * an exact match.
79
         */
80
0
        if (psk_ciphersuite_id != 0) {
81
0
            if (id != psk_ciphersuite_id) {
82
0
                continue;
83
0
            }
84
0
        } else if (psk_hash_alg != PSA_ALG_NONE) {
85
0
            if (mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) info->mac) !=
86
0
                psk_hash_alg) {
87
0
                continue;
88
0
            }
89
0
        }
90
91
0
        *selected_ciphersuite_info = info;
92
0
        return;
93
0
    }
94
95
0
    MBEDTLS_SSL_DEBUG_MSG(1, ("No matched ciphersuite, psk_ciphersuite_id=%x, psk_hash_alg=%lx",
96
0
                              (unsigned) psk_ciphersuite_id,
97
0
                              (unsigned long) psk_hash_alg));
98
0
}
99
100
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
101
/* From RFC 8446:
102
 *
103
 *   enum { psk_ke(0), psk_dhe_ke(1), (255) } PskKeyExchangeMode;
104
 *   struct {
105
 *       PskKeyExchangeMode ke_modes<1..255>;
106
 *   } PskKeyExchangeModes;
107
 */
108
MBEDTLS_CHECK_RETURN_CRITICAL
109
static int ssl_tls13_parse_key_exchange_modes_ext(mbedtls_ssl_context *ssl,
110
                                                  const unsigned char *buf,
111
                                                  const unsigned char *end)
112
0
{
113
0
    const unsigned char *p = buf;
114
0
    size_t ke_modes_len;
115
0
    int ke_modes = 0;
116
117
    /* Read ke_modes length (1 Byte) */
118
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 1);
119
0
    ke_modes_len = *p++;
120
    /* Currently, there are only two PSK modes, so even without looking
121
     * at the content, something's wrong if the list has more than 2 items. */
122
0
    if (ke_modes_len > 2) {
123
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
124
0
                                     MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
125
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
126
0
    }
127
128
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, ke_modes_len);
129
130
0
    while (ke_modes_len-- != 0) {
131
0
        switch (*p++) {
132
0
            case MBEDTLS_SSL_TLS1_3_PSK_MODE_PURE:
133
0
                ke_modes |= MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
134
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("Found PSK KEX MODE"));
135
0
                break;
136
0
            case MBEDTLS_SSL_TLS1_3_PSK_MODE_ECDHE:
137
0
                ke_modes |= MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
138
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("Found PSK_EPHEMERAL KEX MODE"));
139
0
                break;
140
0
            default:
141
0
                MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
142
0
                                             MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
143
0
                return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
144
0
        }
145
0
    }
146
147
0
    ssl->handshake->tls13_kex_modes = ke_modes;
148
0
    return 0;
149
0
}
150
151
/*
152
 * Non-error return values of
153
 * ssl_tls13_offered_psks_check_identity_match_ticket() and
154
 * ssl_tls13_offered_psks_check_identity_match(). They are positive to
155
 * not collide with error codes that are negative. Zero
156
 * (SSL_TLS1_3_PSK_IDENTITY_MATCH) in case of success as it may be propagated
157
 * up by the callers of this function as a generic success condition.
158
 *
159
 * The return value SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE means
160
 * that the pre-shared-key identity matches that of a ticket or an externally-
161
 * provisioned pre-shared-key. We have thus been able to retrieve the
162
 * attributes of the pre-shared-key but at least one of them does not meet
163
 * some criteria and the pre-shared-key cannot be used. For example, a ticket
164
 * is expired or its version is not TLS 1.3. Note eventually that the return
165
 * value SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE does not have
166
 * anything to do with binder check. A binder check is done only when a
167
 * suitable pre-shared-key has been selected and only for that selected
168
 * pre-shared-key: if the binder check fails, we fail the handshake and we do
169
 * not try to find another pre-shared-key for which the binder check would
170
 * succeed as recommended by the specification.
171
 */
172
0
#define SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH 2
173
0
#define SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE 1
174
0
#define SSL_TLS1_3_PSK_IDENTITY_MATCH 0
175
176
MBEDTLS_CHECK_RETURN_CRITICAL
177
static int ssl_tls13_key_exchange_is_psk_available(mbedtls_ssl_context *ssl);
178
MBEDTLS_CHECK_RETURN_CRITICAL
179
static int ssl_tls13_key_exchange_is_psk_ephemeral_available(mbedtls_ssl_context *ssl);
180
181
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
182
MBEDTLS_CHECK_RETURN_CRITICAL
183
static int ssl_tls13_offered_psks_check_identity_match_ticket(
184
    mbedtls_ssl_context *ssl,
185
    const unsigned char *identity,
186
    size_t identity_len,
187
    uint32_t obfuscated_ticket_age,
188
    mbedtls_ssl_session *session)
189
0
{
190
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
191
0
    unsigned char *ticket_buffer;
192
0
#if defined(MBEDTLS_HAVE_TIME)
193
0
    mbedtls_ms_time_t now;
194
0
    mbedtls_ms_time_t server_age;
195
0
    uint32_t client_age;
196
0
    mbedtls_ms_time_t age_diff;
197
0
#endif
198
199
0
    ((void) obfuscated_ticket_age);
200
201
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> check_identity_match_ticket"));
202
203
    /* Ticket parser is not configured, Skip */
204
0
    if (ssl->conf->f_ticket_parse == NULL || identity_len == 0) {
205
0
        return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
206
0
    }
207
208
    /* We create a copy of the encrypted ticket since the ticket parsing
209
     * function is allowed to use its input buffer as an output buffer
210
     * (in-place decryption). We do, however, need the original buffer for
211
     * computing the PSK binder value.
212
     */
213
0
    ticket_buffer = mbedtls_calloc(1, identity_len);
214
0
    if (ticket_buffer == NULL) {
215
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
216
0
    }
217
0
    memcpy(ticket_buffer, identity, identity_len);
218
219
0
    ret = ssl->conf->f_ticket_parse(ssl->conf->p_ticket,
220
0
                                    session,
221
0
                                    ticket_buffer, identity_len);
222
0
    switch (ret) {
223
0
        case 0:
224
0
            ret = SSL_TLS1_3_PSK_IDENTITY_MATCH;
225
0
            break;
226
227
0
        case MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED:
228
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is expired"));
229
0
            ret = SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
230
0
            break;
231
232
0
        case MBEDTLS_ERR_SSL_INVALID_MAC:
233
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("ticket is not authentic"));
234
0
            ret = SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
235
0
            break;
236
237
0
        default:
238
0
            MBEDTLS_SSL_DEBUG_RET(1, "ticket_parse", ret);
239
0
            ret = SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
240
0
    }
241
242
    /* We delete the temporary buffer */
243
0
    mbedtls_free(ticket_buffer);
244
245
0
    if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
246
0
        goto exit;
247
0
    }
248
249
    /*
250
     * The identity matches that of a ticket. Now check that it has suitable
251
     * attributes and bet it will not be the case.
252
     */
253
0
    ret = SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
254
255
0
    if (session->tls_version != MBEDTLS_SSL_VERSION_TLS1_3) {
256
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("Ticket TLS version is not 1.3."));
257
0
        goto exit;
258
0
    }
259
260
0
#if defined(MBEDTLS_HAVE_TIME)
261
0
    now = mbedtls_ms_time();
262
263
0
    if (now < session->ticket_creation_time) {
264
0
        MBEDTLS_SSL_DEBUG_MSG(
265
0
            3, ("Invalid ticket creation time ( now = %" MBEDTLS_PRINTF_MS_TIME
266
0
                ", creation_time = %" MBEDTLS_PRINTF_MS_TIME " )",
267
0
                now, session->ticket_creation_time));
268
0
        goto exit;
269
0
    }
270
271
0
    server_age = now - session->ticket_creation_time;
272
273
    /* RFC 8446 section 4.6.1
274
     *
275
     * Servers MUST NOT use any value greater than 604800 seconds (7 days).
276
     *
277
     * RFC 8446 section 4.2.11.1
278
     *
279
     * Clients MUST NOT attempt to use tickets which have ages greater than
280
     * the "ticket_lifetime" value which was provided with the ticket.
281
     *
282
     */
283
0
    if (server_age > MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME * 1000) {
284
0
        MBEDTLS_SSL_DEBUG_MSG(
285
0
            3, ("Ticket age exceeds limitation ticket_age = %" MBEDTLS_PRINTF_MS_TIME,
286
0
                server_age));
287
0
        goto exit;
288
0
    }
289
290
    /* RFC 8446 section 4.2.10
291
     *
292
     * For PSKs provisioned via NewSessionTicket, a server MUST validate that
293
     * the ticket age for the selected PSK identity (computed by subtracting
294
     * ticket_age_add from PskIdentity.obfuscated_ticket_age modulo 2^32) is
295
     * within a small tolerance of the time since the ticket was issued.
296
     *
297
     * NOTE: The typical accuracy of an RTC crystal is ±100 to ±20 parts per
298
     *       million (360 to 72 milliseconds per hour). Default tolerance
299
     *       window is 6s, thus in the worst case clients and servers must
300
     *       sync up their system time every 6000/360/2~=8 hours.
301
     */
302
0
    client_age = obfuscated_ticket_age - session->ticket_age_add;
303
0
    age_diff = server_age - (mbedtls_ms_time_t) client_age;
304
0
    if (age_diff < -MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE ||
305
0
        age_diff > MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE) {
306
0
        MBEDTLS_SSL_DEBUG_MSG(
307
0
            3, ("Ticket age outside tolerance window ( diff = %"
308
0
                MBEDTLS_PRINTF_MS_TIME ")",
309
0
                age_diff));
310
0
        goto exit;
311
0
    }
312
0
#endif /* MBEDTLS_HAVE_TIME */
313
314
    /*
315
     * All good, we have found a suitable ticket.
316
     */
317
0
    ret = SSL_TLS1_3_PSK_IDENTITY_MATCH;
318
319
0
exit:
320
0
    if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
321
0
        mbedtls_ssl_session_free(session);
322
0
    }
323
324
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= check_identity_match_ticket"));
325
0
    return ret;
326
0
}
327
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
328
329
MBEDTLS_CHECK_RETURN_CRITICAL
330
static int ssl_tls13_offered_psks_check_identity_match(
331
    mbedtls_ssl_context *ssl,
332
    const unsigned char *identity,
333
    size_t identity_len,
334
    uint32_t obfuscated_ticket_age,
335
    int *psk_type,
336
    mbedtls_ssl_session *session)
337
0
{
338
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
339
340
0
    ((void) session);
341
0
    ((void) obfuscated_ticket_age);
342
0
    *psk_type = MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL;
343
344
0
    MBEDTLS_SSL_DEBUG_BUF(4, "identity", identity, identity_len);
345
346
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
347
0
    ret = ssl_tls13_offered_psks_check_identity_match_ticket(
348
0
        ssl, identity, identity_len, obfuscated_ticket_age, session);
349
0
    if (ret == SSL_TLS1_3_PSK_IDENTITY_MATCH) {
350
0
        *psk_type = MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION;
351
0
        ret = mbedtls_ssl_set_hs_psk(ssl,
352
0
                                     session->resumption_key,
353
0
                                     session->resumption_key_len);
354
0
        if (ret != 0) {
355
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
356
0
            return ret;
357
0
        }
358
359
0
        MBEDTLS_SSL_DEBUG_BUF(4, "Ticket-resumed PSK:",
360
0
                              session->resumption_key,
361
0
                              session->resumption_key_len);
362
0
        MBEDTLS_SSL_DEBUG_MSG(4, ("ticket: obfuscated_ticket_age: %u",
363
0
                                  (unsigned) obfuscated_ticket_age));
364
0
        return SSL_TLS1_3_PSK_IDENTITY_MATCH;
365
0
    } else if (ret == SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE) {
366
0
        return SSL_TLS1_3_PSK_IDENTITY_MATCH_BUT_PSK_NOT_USABLE;
367
0
    }
368
0
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
369
370
    /* Check identity with external configured function */
371
0
    if (ssl->conf->f_psk != NULL) {
372
0
        if (ssl->conf->f_psk(
373
0
                ssl->conf->p_psk, ssl, identity, identity_len) == 0) {
374
0
            return SSL_TLS1_3_PSK_IDENTITY_MATCH;
375
0
        }
376
0
        return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
377
0
    }
378
379
0
    MBEDTLS_SSL_DEBUG_BUF(5, "identity", identity, identity_len);
380
    /* Check identity with pre-configured psk */
381
0
    if (ssl->conf->psk_identity != NULL &&
382
0
        identity_len == ssl->conf->psk_identity_len &&
383
0
        mbedtls_ct_memcmp(ssl->conf->psk_identity,
384
0
                          identity, identity_len) == 0) {
385
0
        ret = mbedtls_ssl_set_hs_psk(ssl, ssl->conf->psk, ssl->conf->psk_len);
386
0
        if (ret != 0) {
387
0
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_set_hs_psk", ret);
388
0
            return ret;
389
0
        }
390
0
        return SSL_TLS1_3_PSK_IDENTITY_MATCH;
391
0
    }
392
393
0
    return SSL_TLS1_3_PSK_IDENTITY_DOES_NOT_MATCH;
394
0
}
395
396
/*
397
 * Non-error return values of ssl_tls13_offered_psks_check_binder_match().
398
 * They are positive to not collide with error codes that are negative. Zero
399
 * (SSL_TLS1_3_BINDER_MATCH) in case of success as it may be propagated up
400
 * by the callers of this function as a generic success condition.
401
 */
402
0
#define SSL_TLS1_3_BINDER_DOES_NOT_MATCH 1
403
0
#define SSL_TLS1_3_BINDER_MATCH 0
404
MBEDTLS_CHECK_RETURN_CRITICAL
405
static int ssl_tls13_offered_psks_check_binder_match(
406
    mbedtls_ssl_context *ssl,
407
    const unsigned char *binder, size_t binder_len,
408
    int psk_type, psa_algorithm_t psk_hash_alg)
409
0
{
410
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
411
412
0
    unsigned char transcript[PSA_HASH_MAX_SIZE];
413
0
    size_t transcript_len;
414
0
    unsigned char *psk;
415
0
    size_t psk_len;
416
0
    unsigned char server_computed_binder[PSA_HASH_MAX_SIZE];
417
418
0
    if (binder_len != PSA_HASH_LENGTH(psk_hash_alg)) {
419
0
        return SSL_TLS1_3_BINDER_DOES_NOT_MATCH;
420
0
    }
421
422
    /* Get current state of handshake transcript. */
423
0
    ret = mbedtls_ssl_get_handshake_transcript(
424
0
        ssl, mbedtls_md_type_from_psa_alg(psk_hash_alg),
425
0
        transcript, sizeof(transcript), &transcript_len);
426
0
    if (ret != 0) {
427
0
        return ret;
428
0
    }
429
430
0
    ret = mbedtls_ssl_tls13_export_handshake_psk(ssl, &psk, &psk_len);
431
0
    if (ret != 0) {
432
0
        return ret;
433
0
    }
434
435
0
    ret = mbedtls_ssl_tls13_create_psk_binder(ssl, psk_hash_alg,
436
0
                                              psk, psk_len, psk_type,
437
0
                                              transcript,
438
0
                                              server_computed_binder);
439
#if defined(MBEDTLS_USE_PSA_CRYPTO)
440
    mbedtls_free((void *) psk);
441
#endif
442
0
    if (ret != 0) {
443
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("PSK binder calculation failed."));
444
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
445
0
    }
446
447
0
    MBEDTLS_SSL_DEBUG_BUF(3, "psk binder ( computed ): ",
448
0
                          server_computed_binder, transcript_len);
449
0
    MBEDTLS_SSL_DEBUG_BUF(3, "psk binder ( received ): ", binder, binder_len);
450
451
0
    if (mbedtls_ct_memcmp(server_computed_binder,
452
0
                          binder,
453
0
                          PSA_HASH_LENGTH(psk_hash_alg)) == 0) {
454
0
        return SSL_TLS1_3_BINDER_MATCH;
455
0
    }
456
457
0
    mbedtls_platform_zeroize(server_computed_binder,
458
0
                             sizeof(server_computed_binder));
459
0
    return SSL_TLS1_3_BINDER_DOES_NOT_MATCH;
460
0
}
461
462
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
463
MBEDTLS_CHECK_RETURN_CRITICAL
464
static int ssl_tls13_session_copy_ticket(mbedtls_ssl_session *dst,
465
                                         const mbedtls_ssl_session *src)
466
0
{
467
0
    dst->ticket_age_add = src->ticket_age_add;
468
0
    dst->ticket_flags = src->ticket_flags;
469
0
    dst->resumption_key_len = src->resumption_key_len;
470
0
    if (src->resumption_key_len == 0) {
471
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
472
0
    }
473
0
    memcpy(dst->resumption_key, src->resumption_key, src->resumption_key_len);
474
475
0
#if defined(MBEDTLS_SSL_EARLY_DATA)
476
0
    dst->max_early_data_size = src->max_early_data_size;
477
478
0
#if defined(MBEDTLS_SSL_ALPN)
479
0
    int ret = mbedtls_ssl_session_set_ticket_alpn(dst, src->ticket_alpn);
480
0
    if (ret != 0) {
481
0
        return ret;
482
0
    }
483
0
#endif /* MBEDTLS_SSL_ALPN */
484
0
#endif /* MBEDTLS_SSL_EARLY_DATA*/
485
486
0
    return 0;
487
0
}
488
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
489
490
struct psk_attributes {
491
    int type;
492
    int key_exchange_mode;
493
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
494
};
495
1.45k
#define PSK_ATTRIBUTES_INIT { 0, 0, NULL }
496
497
/* Parser for pre_shared_key extension in client hello
498
 *    struct {
499
 *        opaque identity<1..2^16-1>;
500
 *        uint32 obfuscated_ticket_age;
501
 *    } PskIdentity;
502
 *
503
 *    opaque PskBinderEntry<32..255>;
504
 *
505
 *    struct {
506
 *        PskIdentity identities<7..2^16-1>;
507
 *        PskBinderEntry binders<33..2^16-1>;
508
 *    } OfferedPsks;
509
 *
510
 *    struct {
511
 *        select (Handshake.msg_type) {
512
 *            case client_hello: OfferedPsks;
513
 *            ....
514
 *        };
515
 *    } PreSharedKeyExtension;
516
 */
517
MBEDTLS_CHECK_RETURN_CRITICAL
518
static int ssl_tls13_parse_pre_shared_key_ext(
519
    mbedtls_ssl_context *ssl,
520
    const unsigned char *pre_shared_key_ext,
521
    const unsigned char *pre_shared_key_ext_end,
522
    const unsigned char *ciphersuites,
523
    const unsigned char *ciphersuites_end,
524
    struct psk_attributes *psk)
525
0
{
526
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
527
0
    const unsigned char *identities = pre_shared_key_ext;
528
0
    const unsigned char *p_identity_len;
529
0
    size_t identities_len;
530
0
    const unsigned char *identities_end;
531
0
    const unsigned char *binders;
532
0
    const unsigned char *p_binder_len;
533
0
    size_t binders_len;
534
0
    const unsigned char *binders_end;
535
0
    int matched_identity = -1;
536
0
    int identity_id = -1;
537
538
0
    MBEDTLS_SSL_DEBUG_BUF(3, "pre_shared_key extension",
539
0
                          pre_shared_key_ext,
540
0
                          pre_shared_key_ext_end - pre_shared_key_ext);
541
542
    /* identities_len       2 bytes
543
     * identities_data   >= 7 bytes
544
     */
545
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(identities, pre_shared_key_ext_end, 7 + 2);
546
0
    identities_len = MBEDTLS_GET_UINT16_BE(identities, 0);
547
0
    p_identity_len = identities + 2;
548
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p_identity_len, pre_shared_key_ext_end,
549
0
                                 identities_len);
550
0
    identities_end = p_identity_len + identities_len;
551
552
    /* binders_len     2  bytes
553
     * binders      >= 33 bytes
554
     */
555
0
    binders = identities_end;
556
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(binders, pre_shared_key_ext_end, 33 + 2);
557
0
    binders_len = MBEDTLS_GET_UINT16_BE(binders, 0);
558
0
    p_binder_len = binders + 2;
559
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p_binder_len, pre_shared_key_ext_end, binders_len);
560
0
    binders_end = p_binder_len + binders_len;
561
562
0
    ret = ssl->handshake->update_checksum(ssl, pre_shared_key_ext,
563
0
                                          identities_end - pre_shared_key_ext);
564
0
    if (0 != ret) {
565
0
        MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
566
0
        return ret;
567
0
    }
568
569
0
    while (p_identity_len < identities_end && p_binder_len < binders_end) {
570
0
        const unsigned char *identity;
571
0
        size_t identity_len;
572
0
        uint32_t obfuscated_ticket_age;
573
0
        const unsigned char *binder;
574
0
        size_t binder_len;
575
0
        int psk_ciphersuite_id;
576
0
        psa_algorithm_t psk_hash_alg;
577
0
        int allowed_key_exchange_modes;
578
579
0
        mbedtls_ssl_session session;
580
0
        mbedtls_ssl_session_init(&session);
581
582
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p_identity_len, identities_end, 2 + 1 + 4);
583
0
        identity_len = MBEDTLS_GET_UINT16_BE(p_identity_len, 0);
584
0
        identity = p_identity_len + 2;
585
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(identity, identities_end, identity_len + 4);
586
0
        obfuscated_ticket_age = MBEDTLS_GET_UINT32_BE(identity, identity_len);
587
0
        p_identity_len += identity_len + 6;
588
589
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p_binder_len, binders_end, 1 + 32);
590
0
        binder_len = *p_binder_len;
591
0
        binder = p_binder_len + 1;
592
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(binder, binders_end, binder_len);
593
0
        p_binder_len += binder_len + 1;
594
595
0
        identity_id++;
596
0
        if (matched_identity != -1) {
597
0
            continue;
598
0
        }
599
600
0
        ret = ssl_tls13_offered_psks_check_identity_match(
601
0
            ssl, identity, identity_len, obfuscated_ticket_age,
602
0
            &psk->type, &session);
603
0
        if (ret != SSL_TLS1_3_PSK_IDENTITY_MATCH) {
604
0
            continue;
605
0
        }
606
607
0
        MBEDTLS_SSL_DEBUG_MSG(4, ("found matched identity"));
608
609
0
        switch (psk->type) {
610
0
            case MBEDTLS_SSL_TLS1_3_PSK_EXTERNAL:
611
0
                psk_ciphersuite_id = 0;
612
0
                psk_hash_alg = PSA_ALG_SHA_256;
613
0
                allowed_key_exchange_modes =
614
0
                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
615
0
                break;
616
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
617
0
            case MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION:
618
0
                psk_ciphersuite_id = session.ciphersuite;
619
0
                psk_hash_alg = PSA_ALG_NONE;
620
0
                ssl->session_negotiate->ticket_flags = session.ticket_flags;
621
0
                allowed_key_exchange_modes =
622
0
                    session.ticket_flags &
623
0
                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL;
624
0
                break;
625
0
#endif
626
0
            default:
627
0
                return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
628
0
        }
629
630
0
        psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE;
631
632
0
        if ((allowed_key_exchange_modes &
633
0
             MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL) &&
634
0
            ssl_tls13_key_exchange_is_psk_ephemeral_available(ssl)) {
635
0
            psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
636
0
        } else if ((allowed_key_exchange_modes &
637
0
                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK) &&
638
0
                   ssl_tls13_key_exchange_is_psk_available(ssl)) {
639
0
            psk->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
640
0
        }
641
642
0
        if (psk->key_exchange_mode == MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE) {
643
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("No suitable PSK key exchange mode"));
644
0
            continue;
645
0
        }
646
647
0
        ssl_tls13_select_ciphersuite(ssl, ciphersuites, ciphersuites_end,
648
0
                                     psk_ciphersuite_id, psk_hash_alg,
649
0
                                     &psk->ciphersuite_info);
650
651
0
        if (psk->ciphersuite_info == NULL) {
652
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
653
0
            mbedtls_ssl_session_free(&session);
654
0
#endif
655
            /*
656
             * We consider finding a ciphersuite suitable for the PSK as part
657
             * of the validation of its binder. Thus if we do not find one, we
658
             * abort the handshake with a decrypt_error alert.
659
             */
660
0
            MBEDTLS_SSL_PEND_FATAL_ALERT(
661
0
                MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
662
0
                MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
663
0
            return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
664
0
        }
665
666
0
        ret = ssl_tls13_offered_psks_check_binder_match(
667
0
            ssl, binder, binder_len, psk->type,
668
0
            mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) psk->ciphersuite_info->mac));
669
0
        if (ret != SSL_TLS1_3_BINDER_MATCH) {
670
            /* For security reasons, the handshake should be aborted when we
671
             * fail to validate a binder value. See RFC 8446 section 4.2.11.2
672
             * and appendix E.6. */
673
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
674
0
            mbedtls_ssl_session_free(&session);
675
0
#endif
676
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("Invalid binder."));
677
0
            MBEDTLS_SSL_DEBUG_RET(
678
0
                1, "ssl_tls13_offered_psks_check_binder_match", ret);
679
0
            MBEDTLS_SSL_PEND_FATAL_ALERT(
680
0
                MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR,
681
0
                MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
682
0
            return ret;
683
0
        }
684
685
0
        matched_identity = identity_id;
686
687
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
688
0
        if (psk->type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION) {
689
0
            ret = ssl_tls13_session_copy_ticket(ssl->session_negotiate,
690
0
                                                &session);
691
0
            mbedtls_ssl_session_free(&session);
692
0
            if (ret != 0) {
693
0
                return ret;
694
0
            }
695
0
        }
696
0
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
697
0
    }
698
699
0
    if (p_identity_len != identities_end || p_binder_len != binders_end) {
700
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("pre_shared_key extension decode error"));
701
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
702
0
                                     MBEDTLS_ERR_SSL_DECODE_ERROR);
703
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
704
0
    }
705
706
    /* Update the handshake transcript with the binder list. */
707
0
    ret = ssl->handshake->update_checksum(
708
0
        ssl, identities_end, (size_t) (binders_end - identities_end));
709
0
    if (0 != ret) {
710
0
        MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
711
0
        return ret;
712
0
    }
713
0
    if (matched_identity == -1) {
714
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("No usable PSK or ticket."));
715
0
        return MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY;
716
0
    }
717
718
0
    ssl->handshake->selected_identity = (uint16_t) matched_identity;
719
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("Pre shared key found"));
720
721
0
    return 0;
722
0
}
723
724
/*
725
 * struct {
726
 *   select ( Handshake.msg_type ) {
727
 *      ....
728
 *      case server_hello:
729
 *          uint16 selected_identity;
730
 *   }
731
 * } PreSharedKeyExtension;
732
 */
733
static int ssl_tls13_write_server_pre_shared_key_ext(mbedtls_ssl_context *ssl,
734
                                                     unsigned char *buf,
735
                                                     unsigned char *end,
736
                                                     size_t *olen)
737
0
{
738
0
    unsigned char *p = (unsigned char *) buf;
739
740
0
    *olen = 0;
741
742
0
    int not_using_psk = 0;
743
#if defined(MBEDTLS_USE_PSA_CRYPTO)
744
    not_using_psk = (mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque));
745
#else
746
0
    not_using_psk = (ssl->handshake->psk == NULL);
747
0
#endif
748
0
    if (not_using_psk) {
749
        /* We shouldn't have called this extension writer unless we've
750
         * chosen to use a PSK. */
751
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
752
0
    }
753
754
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding pre_shared_key extension"));
755
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 6);
756
757
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_PRE_SHARED_KEY, p, 0);
758
0
    MBEDTLS_PUT_UINT16_BE(2, p, 2);
759
760
0
    MBEDTLS_PUT_UINT16_BE(ssl->handshake->selected_identity, p, 4);
761
762
0
    *olen = 6;
763
764
0
    MBEDTLS_SSL_DEBUG_MSG(4, ("sent selected_identity: %u",
765
0
                              ssl->handshake->selected_identity));
766
767
0
    mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_PRE_SHARED_KEY);
768
769
0
    return 0;
770
0
}
771
772
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
773
774
/* From RFC 8446:
775
 *   struct {
776
 *          ProtocolVersion versions<2..254>;
777
 *   } SupportedVersions;
778
 */
779
MBEDTLS_CHECK_RETURN_CRITICAL
780
static int ssl_tls13_parse_supported_versions_ext(mbedtls_ssl_context *ssl,
781
                                                  const unsigned char *buf,
782
                                                  const unsigned char *end)
783
233
{
784
233
    const unsigned char *p = buf;
785
233
    size_t versions_len;
786
233
    const unsigned char *versions_end;
787
233
    uint16_t tls_version;
788
233
    int found_supported_version = 0;
789
790
233
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 1);
791
232
    versions_len = p[0];
792
232
    p += 1;
793
794
232
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, versions_len);
795
229
    versions_end = p + versions_len;
796
3.22k
    while (p < versions_end) {
797
3.19k
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, versions_end, 2);
798
3.18k
        tls_version = mbedtls_ssl_read_version(p, ssl->conf->transport);
799
3.18k
        p += 2;
800
801
3.18k
        if (MBEDTLS_SSL_VERSION_TLS1_3 == tls_version) {
802
4
            found_supported_version = 1;
803
4
            break;
804
4
        }
805
806
3.18k
        if ((MBEDTLS_SSL_VERSION_TLS1_2 == tls_version) &&
807
189
            mbedtls_ssl_conf_is_tls12_enabled(ssl->conf)) {
808
189
            found_supported_version = 1;
809
189
            break;
810
189
        }
811
3.18k
    }
812
813
222
    if (!found_supported_version) {
814
29
        MBEDTLS_SSL_DEBUG_MSG(1, ("No supported version found."));
815
816
29
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION,
817
29
                                     MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION);
818
29
        return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
819
29
    }
820
821
193
    MBEDTLS_SSL_DEBUG_MSG(1, ("Negotiated version: [%04x]",
822
193
                              (unsigned int) tls_version));
823
824
193
    return (int) tls_version;
825
222
}
826
827
#if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
828
/*
829
 *
830
 * From RFC 8446:
831
 *   enum {
832
 *       ... (0xFFFF)
833
 *   } NamedGroup;
834
 *   struct {
835
 *       NamedGroup named_group_list<2..2^16-1>;
836
 *   } NamedGroupList;
837
 */
838
MBEDTLS_CHECK_RETURN_CRITICAL
839
static int ssl_tls13_parse_supported_groups_ext(mbedtls_ssl_context *ssl,
840
                                                const unsigned char *buf,
841
                                                const unsigned char *end)
842
0
{
843
0
    const unsigned char *p = buf;
844
0
    size_t named_group_list_len;
845
0
    const unsigned char *named_group_list_end;
846
847
0
    MBEDTLS_SSL_DEBUG_BUF(3, "supported_groups extension", p, end - buf);
848
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
849
0
    named_group_list_len = MBEDTLS_GET_UINT16_BE(p, 0);
850
0
    p += 2;
851
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, named_group_list_len);
852
0
    named_group_list_end = p + named_group_list_len;
853
0
    ssl->handshake->hrr_selected_group = 0;
854
855
0
    while (p < named_group_list_end) {
856
0
        uint16_t named_group;
857
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, named_group_list_end, 2);
858
0
        named_group = MBEDTLS_GET_UINT16_BE(p, 0);
859
0
        p += 2;
860
861
0
        MBEDTLS_SSL_DEBUG_MSG(2,
862
0
                              ("got named group: %s(%04x)",
863
0
                               mbedtls_ssl_named_group_to_str(named_group),
864
0
                               named_group));
865
866
0
        if (!mbedtls_ssl_named_group_is_offered(ssl, named_group) ||
867
0
            !mbedtls_ssl_named_group_is_supported(named_group) ||
868
0
            ssl->handshake->hrr_selected_group != 0) {
869
0
            continue;
870
0
        }
871
872
0
        MBEDTLS_SSL_DEBUG_MSG(2,
873
0
                              ("add named group %s(%04x) into received list.",
874
0
                               mbedtls_ssl_named_group_to_str(named_group),
875
0
                               named_group));
876
877
0
        ssl->handshake->hrr_selected_group = named_group;
878
0
    }
879
880
0
    return 0;
881
882
0
}
883
#endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH */
884
885
0
#define SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH 1
886
887
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
888
/*
889
 *  ssl_tls13_parse_key_shares_ext() verifies whether the information in the
890
 *  extension is correct and stores the first acceptable key share and its
891
 *  associated group.
892
 *
893
 *  Possible return values are:
894
 *  - 0: Successful processing of the client provided key share extension.
895
 *  - SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH: The key shares provided by
896
 *    the client does not match a group supported by the server. A
897
 *    HelloRetryRequest will be needed.
898
 *  - A negative value for fatal errors.
899
 */
900
MBEDTLS_CHECK_RETURN_CRITICAL
901
static int ssl_tls13_parse_key_shares_ext(mbedtls_ssl_context *ssl,
902
                                          const unsigned char *buf,
903
                                          const unsigned char *end)
904
0
{
905
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
906
0
    unsigned char const *p = buf;
907
0
    unsigned char const *client_shares_end;
908
0
    size_t client_shares_len;
909
910
    /* From RFC 8446:
911
     *
912
     * struct {
913
     *     KeyShareEntry client_shares<0..2^16-1>;
914
     * } KeyShareClientHello;
915
     *
916
     */
917
918
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 2);
919
0
    client_shares_len = MBEDTLS_GET_UINT16_BE(p, 0);
920
0
    p += 2;
921
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, client_shares_len);
922
923
0
    ssl->handshake->offered_group_id = 0;
924
0
    client_shares_end = p + client_shares_len;
925
926
    /* We try to find a suitable key share entry and copy it to the
927
     * handshake context. Later, we have to find out whether we can do
928
     * something with the provided key share or whether we have to
929
     * dismiss it and send a HelloRetryRequest message.
930
     */
931
932
0
    while (p < client_shares_end) {
933
0
        uint16_t group;
934
0
        size_t key_exchange_len;
935
0
        const unsigned char *key_exchange;
936
937
        /*
938
         * struct {
939
         *    NamedGroup group;
940
         *    opaque key_exchange<1..2^16-1>;
941
         * } KeyShareEntry;
942
         */
943
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, client_shares_end, 4);
944
0
        group = MBEDTLS_GET_UINT16_BE(p, 0);
945
0
        key_exchange_len = MBEDTLS_GET_UINT16_BE(p, 2);
946
0
        p += 4;
947
0
        key_exchange = p;
948
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, client_shares_end, key_exchange_len);
949
0
        p += key_exchange_len;
950
951
        /* Continue parsing even if we have already found a match,
952
         * for input validation purposes.
953
         */
954
0
        if (!mbedtls_ssl_named_group_is_offered(ssl, group) ||
955
0
            !mbedtls_ssl_named_group_is_supported(group) ||
956
0
            ssl->handshake->offered_group_id != 0) {
957
0
            continue;
958
0
        }
959
960
        /*
961
         * ECDHE and FFDHE groups are supported
962
         */
963
0
        if (mbedtls_ssl_tls13_named_group_is_ecdhe(group) ||
964
0
            mbedtls_ssl_tls13_named_group_is_ffdh(group)) {
965
0
            MBEDTLS_SSL_DEBUG_MSG(2, ("ECDH/FFDH group: %s (%04x)",
966
0
                                      mbedtls_ssl_named_group_to_str(group),
967
0
                                      group));
968
0
            ret = mbedtls_ssl_tls13_read_public_xxdhe_share(
969
0
                ssl, key_exchange - 2, key_exchange_len + 2);
970
0
            if (ret != 0) {
971
0
                return ret;
972
0
            }
973
974
0
        } else {
975
0
            MBEDTLS_SSL_DEBUG_MSG(4, ("Unrecognized NamedGroup %u",
976
0
                                      (unsigned) group));
977
0
            continue;
978
0
        }
979
980
0
        ssl->handshake->offered_group_id = group;
981
0
    }
982
983
984
0
    if (ssl->handshake->offered_group_id == 0) {
985
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("no matching key share"));
986
0
        return SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH;
987
0
    }
988
0
    return 0;
989
0
}
990
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
991
992
MBEDTLS_CHECK_RETURN_CRITICAL
993
static int ssl_tls13_client_hello_has_exts(mbedtls_ssl_context *ssl,
994
                                           int exts_mask)
995
0
{
996
0
    int masked = ssl->handshake->received_extensions & exts_mask;
997
0
    return masked == exts_mask;
998
0
}
999
1000
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1001
MBEDTLS_CHECK_RETURN_CRITICAL
1002
static int ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(
1003
    mbedtls_ssl_context *ssl)
1004
0
{
1005
0
    return ssl_tls13_client_hello_has_exts(
1006
0
        ssl,
1007
0
        MBEDTLS_SSL_EXT_MASK(SUPPORTED_GROUPS) |
1008
0
        MBEDTLS_SSL_EXT_MASK(KEY_SHARE)        |
1009
0
        MBEDTLS_SSL_EXT_MASK(SIG_ALG));
1010
0
}
1011
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
1012
1013
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED)
1014
MBEDTLS_CHECK_RETURN_CRITICAL
1015
static int ssl_tls13_client_hello_has_exts_for_psk_key_exchange(
1016
    mbedtls_ssl_context *ssl)
1017
0
{
1018
0
    return ssl_tls13_client_hello_has_exts(
1019
0
        ssl,
1020
0
        MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)          |
1021
0
        MBEDTLS_SSL_EXT_MASK(PSK_KEY_EXCHANGE_MODES));
1022
0
}
1023
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED */
1024
1025
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
1026
MBEDTLS_CHECK_RETURN_CRITICAL
1027
static int ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(
1028
    mbedtls_ssl_context *ssl)
1029
0
{
1030
0
    return ssl_tls13_client_hello_has_exts(
1031
0
        ssl,
1032
0
        MBEDTLS_SSL_EXT_MASK(SUPPORTED_GROUPS)        |
1033
0
        MBEDTLS_SSL_EXT_MASK(KEY_SHARE)               |
1034
0
        MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)          |
1035
0
        MBEDTLS_SSL_EXT_MASK(PSK_KEY_EXCHANGE_MODES));
1036
0
}
1037
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED */
1038
1039
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1040
MBEDTLS_CHECK_RETURN_CRITICAL
1041
static int ssl_tls13_key_exchange_is_psk_available(mbedtls_ssl_context *ssl)
1042
0
{
1043
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED)
1044
0
    return mbedtls_ssl_conf_tls13_is_psk_enabled(ssl) &&
1045
0
           mbedtls_ssl_tls13_is_psk_supported(ssl) &&
1046
0
           ssl_tls13_client_hello_has_exts_for_psk_key_exchange(ssl);
1047
#else
1048
    ((void) ssl);
1049
    return 0;
1050
#endif
1051
0
}
1052
1053
MBEDTLS_CHECK_RETURN_CRITICAL
1054
static int ssl_tls13_key_exchange_is_psk_ephemeral_available(mbedtls_ssl_context *ssl)
1055
0
{
1056
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
1057
0
    return mbedtls_ssl_conf_tls13_is_psk_ephemeral_enabled(ssl) &&
1058
0
           mbedtls_ssl_tls13_is_psk_ephemeral_supported(ssl) &&
1059
0
           ssl_tls13_client_hello_has_exts_for_psk_ephemeral_key_exchange(ssl);
1060
#else
1061
    ((void) ssl);
1062
    return 0;
1063
#endif
1064
0
}
1065
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1066
1067
MBEDTLS_CHECK_RETURN_CRITICAL
1068
static int ssl_tls13_key_exchange_is_ephemeral_available(mbedtls_ssl_context *ssl)
1069
0
{
1070
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1071
0
    return mbedtls_ssl_conf_tls13_is_ephemeral_enabled(ssl) &&
1072
0
           ssl_tls13_client_hello_has_exts_for_ephemeral_key_exchange(ssl);
1073
#else
1074
    ((void) ssl);
1075
    return 0;
1076
#endif
1077
0
}
1078
1079
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
1080
    defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1081
1082
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1083
static psa_algorithm_t ssl_tls13_iana_sig_alg_to_psa_alg(uint16_t sig_alg)
1084
0
{
1085
0
    switch (sig_alg) {
1086
0
        case MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256:
1087
0
            return PSA_ALG_ECDSA(PSA_ALG_SHA_256);
1088
0
        case MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384:
1089
0
            return PSA_ALG_ECDSA(PSA_ALG_SHA_384);
1090
0
        case MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512:
1091
0
            return PSA_ALG_ECDSA(PSA_ALG_SHA_512);
1092
0
        case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256:
1093
0
            return PSA_ALG_RSA_PSS(PSA_ALG_SHA_256);
1094
0
        case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384:
1095
0
            return PSA_ALG_RSA_PSS(PSA_ALG_SHA_384);
1096
0
        case MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512:
1097
0
            return PSA_ALG_RSA_PSS(PSA_ALG_SHA_512);
1098
0
        case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256:
1099
0
            return PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_256);
1100
0
        case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384:
1101
0
            return PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_384);
1102
0
        case MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512:
1103
0
            return PSA_ALG_RSA_PKCS1V15_SIGN(PSA_ALG_SHA_512);
1104
0
        default:
1105
0
            return PSA_ALG_NONE;
1106
0
    }
1107
0
}
1108
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1109
1110
/*
1111
 * Pick best ( private key, certificate chain ) pair based on the signature
1112
 * algorithms supported by the client.
1113
 */
1114
MBEDTLS_CHECK_RETURN_CRITICAL
1115
static int ssl_tls13_pick_key_cert(mbedtls_ssl_context *ssl)
1116
0
{
1117
0
    mbedtls_ssl_key_cert *key_cert, *key_cert_list;
1118
0
    const uint16_t *sig_alg = ssl->handshake->received_sig_algs;
1119
1120
0
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1121
0
    if (ssl->handshake->sni_key_cert != NULL) {
1122
0
        key_cert_list = ssl->handshake->sni_key_cert;
1123
0
    } else
1124
0
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1125
0
    key_cert_list = ssl->conf->key_cert;
1126
1127
0
    if (key_cert_list == NULL) {
1128
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("server has no certificate"));
1129
0
        return -1;
1130
0
    }
1131
1132
0
    for (; *sig_alg != MBEDTLS_TLS1_3_SIG_NONE; sig_alg++) {
1133
0
        if (!mbedtls_ssl_sig_alg_is_offered(ssl, *sig_alg)) {
1134
0
            continue;
1135
0
        }
1136
1137
0
        if (!mbedtls_ssl_tls13_sig_alg_for_cert_verify_is_supported(*sig_alg)) {
1138
0
            continue;
1139
0
        }
1140
1141
0
        for (key_cert = key_cert_list; key_cert != NULL;
1142
0
             key_cert = key_cert->next) {
1143
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1144
0
            psa_algorithm_t psa_alg = PSA_ALG_NONE;
1145
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1146
1147
0
            MBEDTLS_SSL_DEBUG_CRT(3, "certificate (chain) candidate",
1148
0
                                  key_cert->cert);
1149
1150
            /*
1151
             * This avoids sending the client a cert it'll reject based on
1152
             * keyUsage or other extensions.
1153
             */
1154
0
            if (mbedtls_x509_crt_check_key_usage(
1155
0
                    key_cert->cert, MBEDTLS_X509_KU_DIGITAL_SIGNATURE) != 0 ||
1156
0
                mbedtls_x509_crt_check_extended_key_usage(
1157
0
                    key_cert->cert, MBEDTLS_OID_SERVER_AUTH,
1158
0
                    MBEDTLS_OID_SIZE(MBEDTLS_OID_SERVER_AUTH)) != 0) {
1159
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("certificate mismatch: "
1160
0
                                          "(extended) key usage extension"));
1161
0
                continue;
1162
0
            }
1163
1164
0
            MBEDTLS_SSL_DEBUG_MSG(3,
1165
0
                                  ("ssl_tls13_pick_key_cert:"
1166
0
                                   "check signature algorithm %s [%04x]",
1167
0
                                   mbedtls_ssl_sig_alg_to_str(*sig_alg),
1168
0
                                   *sig_alg));
1169
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1170
            psa_alg = ssl_tls13_iana_sig_alg_to_psa_alg(*sig_alg);
1171
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1172
1173
0
            if (mbedtls_ssl_tls13_check_sig_alg_cert_key_match(
1174
0
                    *sig_alg, &key_cert->cert->pk)
1175
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1176
0
                && psa_alg != PSA_ALG_NONE &&
1177
0
                mbedtls_pk_can_do_ext(&key_cert->cert->pk, psa_alg,
1178
0
                                      PSA_KEY_USAGE_SIGN_HASH) == 1
1179
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1180
0
                ) {
1181
0
                ssl->handshake->key_cert = key_cert;
1182
0
                MBEDTLS_SSL_DEBUG_MSG(3,
1183
0
                                      ("ssl_tls13_pick_key_cert:"
1184
0
                                       "selected signature algorithm"
1185
0
                                       " %s [%04x]",
1186
0
                                       mbedtls_ssl_sig_alg_to_str(*sig_alg),
1187
0
                                       *sig_alg));
1188
0
                MBEDTLS_SSL_DEBUG_CRT(
1189
0
                    3, "selected certificate (chain)",
1190
0
                    ssl->handshake->key_cert->cert);
1191
0
                return 0;
1192
0
            }
1193
0
        }
1194
0
    }
1195
1196
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("ssl_tls13_pick_key_cert:"
1197
0
                              "no suitable certificate found"));
1198
0
    return -1;
1199
0
}
Unexecuted instantiation: ssl_tls13_server.c:ssl_tls13_pick_key_cert
Unexecuted instantiation: ssl_tls13_server.c:ssl_tls13_pick_key_cert
1200
#endif /* MBEDTLS_X509_CRT_PARSE_C &&
1201
          MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
1202
1203
/*
1204
 *
1205
 * STATE HANDLING: ClientHello
1206
 *
1207
 * There are three possible classes of outcomes when parsing the ClientHello:
1208
 *
1209
 * 1) The ClientHello was well-formed and matched the server's configuration.
1210
 *
1211
 *    In this case, the server progresses to sending its ServerHello.
1212
 *
1213
 * 2) The ClientHello was well-formed but didn't match the server's
1214
 *    configuration.
1215
 *
1216
 *    For example, the client might not have offered a key share which
1217
 *    the server supports, or the server might require a cookie.
1218
 *
1219
 *    In this case, the server sends a HelloRetryRequest.
1220
 *
1221
 * 3) The ClientHello was ill-formed
1222
 *
1223
 *    In this case, we abort the handshake.
1224
 *
1225
 */
1226
1227
/*
1228
 * Structure of this message:
1229
 *
1230
 * uint16 ProtocolVersion;
1231
 * opaque Random[32];
1232
 * uint8 CipherSuite[2];    // Cryptographic suite selector
1233
 *
1234
 * struct {
1235
 *      ProtocolVersion legacy_version = 0x0303;    // TLS v1.2
1236
 *      Random random;
1237
 *      opaque legacy_session_id<0..32>;
1238
 *      CipherSuite cipher_suites<2..2^16-2>;
1239
 *      opaque legacy_compression_methods<1..2^8-1>;
1240
 *      Extension extensions<8..2^16-1>;
1241
 * } ClientHello;
1242
 */
1243
1244
0
#define SSL_CLIENT_HELLO_OK           0
1245
0
#define SSL_CLIENT_HELLO_HRR_REQUIRED 1
1246
2.56k
#define SSL_CLIENT_HELLO_TLS1_2       2
1247
1248
MBEDTLS_CHECK_RETURN_CRITICAL
1249
static int ssl_tls13_parse_client_hello(mbedtls_ssl_context *ssl,
1250
                                        const unsigned char *buf,
1251
                                        const unsigned char *end)
1252
1.45k
{
1253
1.45k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1254
1.45k
    const unsigned char *p = buf;
1255
1.45k
    const unsigned char *random;
1256
1.45k
    size_t legacy_session_id_len;
1257
1.45k
    const unsigned char *legacy_session_id;
1258
1.45k
    size_t cipher_suites_len;
1259
1.45k
    const unsigned char *cipher_suites;
1260
1.45k
    const unsigned char *cipher_suites_end;
1261
1.45k
    size_t extensions_len;
1262
1.45k
    const unsigned char *extensions_end;
1263
1.45k
    const unsigned char *supported_versions_data;
1264
1.45k
    const unsigned char *supported_versions_data_end;
1265
1.45k
    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1266
1.45k
    int hrr_required = 0;
1267
1.45k
    int no_usable_share_for_key_agreement = 0;
1268
1269
1.45k
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1270
1.45k
    int got_psk = 0;
1271
1.45k
    struct psk_attributes psk = PSK_ATTRIBUTES_INIT;
1272
1.45k
    const unsigned char *pre_shared_key_ext = NULL;
1273
1.45k
    const unsigned char *pre_shared_key_ext_end = NULL;
1274
1.45k
#endif
1275
1276
    /*
1277
     * ClientHello layout:
1278
     *     0  .   1   protocol version
1279
     *     2  .  33   random bytes
1280
     *    34  .  34   session id length ( 1 byte )
1281
     *    35  . 34+x  session id
1282
     *    ..  .  ..   ciphersuite list length ( 2 bytes )
1283
     *    ..  .  ..   ciphersuite list
1284
     *    ..  .  ..   compression alg. list length ( 1 byte )
1285
     *    ..  .  ..   compression alg. list
1286
     *    ..  .  ..   extensions length ( 2 bytes, optional )
1287
     *    ..  .  ..   extensions ( optional )
1288
     */
1289
1290
    /*
1291
     * Minimal length ( with everything empty and extensions omitted ) is
1292
     * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can
1293
     * read at least up to session id length without worrying.
1294
     */
1295
1.45k
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, 38);
1296
1297
    /* ...
1298
     * ProtocolVersion legacy_version = 0x0303; // TLS 1.2
1299
     * ...
1300
     * with ProtocolVersion defined as:
1301
     * uint16 ProtocolVersion;
1302
     */
1303
1.44k
    if (mbedtls_ssl_read_version(p, ssl->conf->transport) !=
1304
1.44k
        MBEDTLS_SSL_VERSION_TLS1_2) {
1305
26
        MBEDTLS_SSL_DEBUG_MSG(1, ("Unsupported version of TLS."));
1306
26
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION,
1307
26
                                     MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION);
1308
26
        return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1309
26
    }
1310
1.42k
    p += 2;
1311
1312
    /* ...
1313
     * Random random;
1314
     * ...
1315
     * with Random defined as:
1316
     * opaque Random[32];
1317
     */
1318
1.42k
    random = p;
1319
1.42k
    p += MBEDTLS_CLIENT_HELLO_RANDOM_LEN;
1320
1321
    /* ...
1322
     * opaque legacy_session_id<0..32>;
1323
     * ...
1324
     */
1325
1.42k
    legacy_session_id_len = *(p++);
1326
1.42k
    legacy_session_id = p;
1327
1328
    /*
1329
     * Check we have enough data for the legacy session identifier
1330
     * and the ciphersuite list length.
1331
     */
1332
1.42k
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, legacy_session_id_len + 2);
1333
1.41k
    p += legacy_session_id_len;
1334
1335
    /* ...
1336
     * CipherSuite cipher_suites<2..2^16-2>;
1337
     * ...
1338
     * with CipherSuite defined as:
1339
     * uint8 CipherSuite[2];
1340
     */
1341
1.41k
    cipher_suites_len = MBEDTLS_GET_UINT16_BE(p, 0);
1342
1.41k
    p += 2;
1343
1.41k
    cipher_suites = p;
1344
1345
    /*
1346
     * The length of the ciphersuite list has to be even.
1347
     */
1348
1.41k
    if (cipher_suites_len & 1) {
1349
2
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
1350
2
                                     MBEDTLS_ERR_SSL_DECODE_ERROR);
1351
2
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1352
2
    }
1353
1354
    /* Check we have enough data for the ciphersuite list, the legacy
1355
     * compression methods and the length of the extensions.
1356
     *
1357
     * cipher_suites                cipher_suites_len bytes
1358
     * legacy_compression_methods length            1 byte
1359
     */
1360
1.41k
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, cipher_suites_len + 1);
1361
1.39k
    p += cipher_suites_len;
1362
1.39k
    cipher_suites_end = p;
1363
1364
    /* Check if we have enough data for legacy_compression_methods
1365
     * and the length of the extensions (2 bytes).
1366
     */
1367
1.39k
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p + 1, end, p[0] + 2);
1368
1369
    /*
1370
     * Search for the supported versions extension and parse it to determine
1371
     * if the client supports TLS 1.3.
1372
     */
1373
1.38k
    ret = mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts(
1374
1.38k
        ssl, p + 1 + p[0], end,
1375
1.38k
        &supported_versions_data, &supported_versions_data_end);
1376
1.38k
    if (ret < 0) {
1377
56
        MBEDTLS_SSL_DEBUG_RET(1,
1378
56
                              ("mbedtls_ssl_tls13_is_supported_versions_ext_present_in_exts"), ret);
1379
56
        return ret;
1380
56
    }
1381
1382
1.32k
    if (ret == 0) {
1383
1.09k
        MBEDTLS_SSL_DEBUG_MSG(2, ("no supported_versions extension"));
1384
1.09k
        return SSL_CLIENT_HELLO_TLS1_2;
1385
1.09k
    }
1386
1387
233
    if (ret == 1) {
1388
233
        ret = ssl_tls13_parse_supported_versions_ext(ssl,
1389
233
                                                     supported_versions_data,
1390
233
                                                     supported_versions_data_end);
1391
233
        if (ret < 0) {
1392
40
            MBEDTLS_SSL_DEBUG_RET(1,
1393
40
                                  ("ssl_tls13_parse_supported_versions_ext"), ret);
1394
40
            return ret;
1395
40
        }
1396
1397
        /*
1398
         * The supported versions extension was parsed successfully as the
1399
         * value returned by ssl_tls13_parse_supported_versions_ext() is
1400
         * positive. The return value is then equal to
1401
         * MBEDTLS_SSL_VERSION_TLS1_2 or MBEDTLS_SSL_VERSION_TLS1_3, defining
1402
         * the TLS version to negotiate.
1403
         */
1404
193
        if (MBEDTLS_SSL_VERSION_TLS1_2 == ret) {
1405
189
            MBEDTLS_SSL_DEBUG_MSG(2, ("supported_versions without 1.3"));
1406
189
            return SSL_CLIENT_HELLO_TLS1_2;
1407
189
        }
1408
193
    }
1409
1410
    /*
1411
     * We negotiate TLS 1.3.
1412
     */
1413
4
    ssl->tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
1414
4
    ssl->session_negotiate->tls_version = MBEDTLS_SSL_VERSION_TLS1_3;
1415
4
    ssl->session_negotiate->endpoint = ssl->conf->endpoint;
1416
1417
    /* Before doing any crypto, make sure we can. */
1418
4
    ret = mbedtls_ssl_tls13_crypto_init(ssl);
1419
4
    if (ret != 0) {
1420
4
        return ret;
1421
4
    }
1422
1423
    /*
1424
     * We are negotiating the version 1.3 of the protocol. Do what we have
1425
     * postponed: copy of the client random bytes, copy of the legacy session
1426
     * identifier and selection of the TLS 1.3 cipher suite.
1427
     */
1428
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, random bytes",
1429
0
                          random, MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
1430
0
    memcpy(&handshake->randbytes[0], random, MBEDTLS_CLIENT_HELLO_RANDOM_LEN);
1431
1432
0
    if (legacy_session_id_len > sizeof(ssl->session_negotiate->id)) {
1433
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad client hello message"));
1434
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
1435
0
    }
1436
0
    ssl->session_negotiate->id_len = legacy_session_id_len;
1437
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, session id",
1438
0
                          legacy_session_id, legacy_session_id_len);
1439
0
    memcpy(&ssl->session_negotiate->id[0],
1440
0
           legacy_session_id, legacy_session_id_len);
1441
1442
    /*
1443
     * Search for a matching ciphersuite
1444
     */
1445
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello, list of cipher suites",
1446
0
                          cipher_suites, cipher_suites_len);
1447
1448
0
    ssl_tls13_select_ciphersuite(ssl, cipher_suites, cipher_suites_end,
1449
0
                                 0, PSA_ALG_NONE, &handshake->ciphersuite_info);
1450
1451
0
    if (handshake->ciphersuite_info == NULL) {
1452
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
1453
0
                                     MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
1454
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
1455
0
    }
1456
0
    ssl->session_negotiate->ciphersuite = handshake->ciphersuite_info->id;
1457
1458
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("selected ciphersuite: %04x - %s",
1459
0
                              ((unsigned) handshake->ciphersuite_info->id),
1460
0
                              handshake->ciphersuite_info->name));
1461
1462
    /* ...
1463
     * opaque legacy_compression_methods<1..2^8-1>;
1464
     * ...
1465
     */
1466
0
    if (p[0] != 1 || p[1] != MBEDTLS_SSL_COMPRESS_NULL) {
1467
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad legacy compression method"));
1468
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1469
0
                                     MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1470
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1471
0
    }
1472
0
    p += 2;
1473
1474
    /* ...
1475
     * Extension extensions<8..2^16-1>;
1476
     * ...
1477
     * with Extension defined as:
1478
     * struct {
1479
     *    ExtensionType extension_type;
1480
     *    opaque extension_data<0..2^16-1>;
1481
     * } Extension;
1482
     */
1483
0
    extensions_len = MBEDTLS_GET_UINT16_BE(p, 0);
1484
0
    p += 2;
1485
0
    MBEDTLS_SSL_CHK_BUF_READ_PTR(p, end, extensions_len);
1486
0
    extensions_end = p + extensions_len;
1487
1488
0
    MBEDTLS_SSL_DEBUG_BUF(3, "client hello extensions", p, extensions_len);
1489
0
    handshake->received_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
1490
1491
0
    while (p < extensions_end) {
1492
0
        unsigned int extension_type;
1493
0
        size_t extension_data_len;
1494
0
        const unsigned char *extension_data_end;
1495
0
        uint32_t allowed_exts = MBEDTLS_SSL_TLS1_3_ALLOWED_EXTS_OF_CH;
1496
1497
0
        if (ssl->handshake->hello_retry_request_flag) {
1498
            /* Do not accept early data extension in 2nd ClientHello */
1499
0
            allowed_exts &= ~MBEDTLS_SSL_EXT_MASK(EARLY_DATA);
1500
0
        }
1501
1502
        /* RFC 8446, section 4.2.11
1503
         *
1504
         * The "pre_shared_key" extension MUST be the last extension in the
1505
         * ClientHello (this facilitates implementation as described below).
1506
         * Servers MUST check that it is the last extension and otherwise fail
1507
         * the handshake with an "illegal_parameter" alert.
1508
         */
1509
0
        if (handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)) {
1510
0
            MBEDTLS_SSL_DEBUG_MSG(
1511
0
                3, ("pre_shared_key is not last extension."));
1512
0
            MBEDTLS_SSL_PEND_FATAL_ALERT(
1513
0
                MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1514
0
                MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1515
0
            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1516
0
        }
1517
1518
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, 4);
1519
0
        extension_type = MBEDTLS_GET_UINT16_BE(p, 0);
1520
0
        extension_data_len = MBEDTLS_GET_UINT16_BE(p, 2);
1521
0
        p += 4;
1522
1523
0
        MBEDTLS_SSL_CHK_BUF_READ_PTR(p, extensions_end, extension_data_len);
1524
0
        extension_data_end = p + extension_data_len;
1525
1526
0
        ret = mbedtls_ssl_tls13_check_received_extension(
1527
0
            ssl, MBEDTLS_SSL_HS_CLIENT_HELLO, extension_type,
1528
0
            allowed_exts);
1529
0
        if (ret != 0) {
1530
0
            return ret;
1531
0
        }
1532
1533
0
        switch (extension_type) {
1534
0
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1535
0
            case MBEDTLS_TLS_EXT_SERVERNAME:
1536
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found ServerName extension"));
1537
0
                ret = mbedtls_ssl_parse_server_name_ext(ssl, p,
1538
0
                                                        extension_data_end);
1539
0
                if (ret != 0) {
1540
0
                    MBEDTLS_SSL_DEBUG_RET(
1541
0
                        1, "mbedtls_ssl_parse_servername_ext", ret);
1542
0
                    return ret;
1543
0
                }
1544
0
                break;
1545
0
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1546
1547
0
#if defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)
1548
0
            case MBEDTLS_TLS_EXT_SUPPORTED_GROUPS:
1549
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found supported group extension"));
1550
1551
                /* Supported Groups Extension
1552
                 *
1553
                 * When sent by the client, the "supported_groups" extension
1554
                 * indicates the named groups which the client supports,
1555
                 * ordered from most preferred to least preferred.
1556
                 */
1557
0
                ret = ssl_tls13_parse_supported_groups_ext(
1558
0
                    ssl, p, extension_data_end);
1559
0
                if (ret != 0) {
1560
0
                    MBEDTLS_SSL_DEBUG_RET(
1561
0
                        1, "ssl_tls13_parse_supported_groups_ext", ret);
1562
0
                    return ret;
1563
0
                }
1564
1565
0
                break;
1566
0
#endif /* PSA_WANT_ALG_ECDH || PSA_WANT_ALG_FFDH*/
1567
1568
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
1569
0
            case MBEDTLS_TLS_EXT_KEY_SHARE:
1570
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found key share extension"));
1571
1572
                /*
1573
                 * Key Share Extension
1574
                 *
1575
                 * When sent by the client, the "key_share" extension
1576
                 * contains the endpoint's cryptographic parameters for
1577
                 * ECDHE/DHE key establishment methods.
1578
                 */
1579
0
                ret = ssl_tls13_parse_key_shares_ext(
1580
0
                    ssl, p, extension_data_end);
1581
0
                if (ret == SSL_TLS1_3_PARSE_KEY_SHARES_EXT_NO_MATCH) {
1582
0
                    MBEDTLS_SSL_DEBUG_MSG(2, ("No usable share for key agreement."));
1583
0
                    no_usable_share_for_key_agreement = 1;
1584
0
                }
1585
1586
0
                if (ret < 0) {
1587
0
                    MBEDTLS_SSL_DEBUG_RET(
1588
0
                        1, "ssl_tls13_parse_key_shares_ext", ret);
1589
0
                    return ret;
1590
0
                }
1591
1592
0
                break;
1593
0
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
1594
1595
0
            case MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS:
1596
                /* Already parsed */
1597
0
                break;
1598
1599
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1600
0
            case MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES:
1601
0
                MBEDTLS_SSL_DEBUG_MSG(
1602
0
                    3, ("found psk key exchange modes extension"));
1603
1604
0
                ret = ssl_tls13_parse_key_exchange_modes_ext(
1605
0
                    ssl, p, extension_data_end);
1606
0
                if (ret != 0) {
1607
0
                    MBEDTLS_SSL_DEBUG_RET(
1608
0
                        1, "ssl_tls13_parse_key_exchange_modes_ext", ret);
1609
0
                    return ret;
1610
0
                }
1611
1612
0
                break;
1613
0
#endif
1614
1615
0
            case MBEDTLS_TLS_EXT_PRE_SHARED_KEY:
1616
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found pre_shared_key extension"));
1617
0
                if ((handshake->received_extensions &
1618
0
                     MBEDTLS_SSL_EXT_MASK(PSK_KEY_EXCHANGE_MODES)) == 0) {
1619
0
                    MBEDTLS_SSL_PEND_FATAL_ALERT(
1620
0
                        MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1621
0
                        MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1622
0
                    return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1623
0
                }
1624
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1625
                /* Delay processing of the PSK identity once we have
1626
                 * found out which algorithms to use. We keep a pointer
1627
                 * to the buffer and the size for later processing.
1628
                 */
1629
0
                pre_shared_key_ext = p;
1630
0
                pre_shared_key_ext_end = extension_data_end;
1631
0
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1632
0
                break;
1633
1634
0
#if defined(MBEDTLS_SSL_ALPN)
1635
0
            case MBEDTLS_TLS_EXT_ALPN:
1636
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found alpn extension"));
1637
1638
0
                ret = mbedtls_ssl_parse_alpn_ext(ssl, p, extension_data_end);
1639
0
                if (ret != 0) {
1640
0
                    MBEDTLS_SSL_DEBUG_RET(
1641
0
                        1, ("mbedtls_ssl_parse_alpn_ext"), ret);
1642
0
                    return ret;
1643
0
                }
1644
0
                break;
1645
0
#endif /* MBEDTLS_SSL_ALPN */
1646
1647
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
1648
0
            case MBEDTLS_TLS_EXT_SIG_ALG:
1649
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found signature_algorithms extension"));
1650
1651
0
                ret = mbedtls_ssl_parse_sig_alg_ext(
1652
0
                    ssl, p, extension_data_end);
1653
0
                if (ret != 0) {
1654
0
                    MBEDTLS_SSL_DEBUG_RET(
1655
0
                        1, "mbedtls_ssl_parse_sig_alg_ext", ret);
1656
0
                    return ret;
1657
0
                }
1658
0
                break;
1659
0
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
1660
1661
0
#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
1662
0
            case MBEDTLS_TLS_EXT_RECORD_SIZE_LIMIT:
1663
0
                MBEDTLS_SSL_DEBUG_MSG(3, ("found record_size_limit extension"));
1664
1665
0
                ret = mbedtls_ssl_tls13_parse_record_size_limit_ext(
1666
0
                    ssl, p, extension_data_end);
1667
0
                if (ret != 0) {
1668
0
                    MBEDTLS_SSL_DEBUG_RET(
1669
0
                        1, ("mbedtls_ssl_tls13_parse_record_size_limit_ext"), ret);
1670
0
                    return ret;
1671
0
                }
1672
0
                break;
1673
0
#endif /* MBEDTLS_SSL_RECORD_SIZE_LIMIT */
1674
1675
0
            default:
1676
0
                MBEDTLS_SSL_PRINT_EXT(
1677
0
                    3, MBEDTLS_SSL_HS_CLIENT_HELLO,
1678
0
                    extension_type, "( ignored )");
1679
0
                break;
1680
0
        }
1681
1682
0
        p += extension_data_len;
1683
0
    }
1684
1685
0
    MBEDTLS_SSL_PRINT_EXTS(3, MBEDTLS_SSL_HS_CLIENT_HELLO,
1686
0
                           handshake->received_extensions);
1687
1688
0
    ret = mbedtls_ssl_add_hs_hdr_to_checksum(ssl,
1689
0
                                             MBEDTLS_SSL_HS_CLIENT_HELLO,
1690
0
                                             p - buf);
1691
0
    if (0 != ret) {
1692
0
        MBEDTLS_SSL_DEBUG_RET(1, ("mbedtls_ssl_add_hs_hdr_to_checksum"), ret);
1693
0
        return ret;
1694
0
    }
1695
1696
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1697
    /* Update checksum with either
1698
     * - The entire content of the CH message, if no PSK extension is present
1699
     * - The content up to but excluding the PSK extension, if present.
1700
     * Always parse the pre-shared-key extension when present in the
1701
     * ClientHello even if some pre-requisites for PSK key exchange modes are
1702
     * not met. That way we always validate the syntax of the extension.
1703
     */
1704
0
    if (handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(PRE_SHARED_KEY)) {
1705
0
        ret = handshake->update_checksum(ssl, buf,
1706
0
                                         pre_shared_key_ext - buf);
1707
0
        if (0 != ret) {
1708
0
            MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
1709
0
            return ret;
1710
0
        }
1711
0
        ret = ssl_tls13_parse_pre_shared_key_ext(ssl,
1712
0
                                                 pre_shared_key_ext,
1713
0
                                                 pre_shared_key_ext_end,
1714
0
                                                 cipher_suites,
1715
0
                                                 cipher_suites_end,
1716
0
                                                 &psk);
1717
0
        if (ret == 0) {
1718
0
            got_psk = 1;
1719
0
        } else if (ret != MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY) {
1720
0
            MBEDTLS_SSL_DEBUG_RET(
1721
0
                1, "ssl_tls13_parse_pre_shared_key_ext", ret);
1722
0
            return ret;
1723
0
        }
1724
0
    } else
1725
0
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED */
1726
0
    {
1727
0
        ret = handshake->update_checksum(ssl, buf, p - buf);
1728
0
        if (0 != ret) {
1729
0
            MBEDTLS_SSL_DEBUG_RET(1, ("update_checksum"), ret);
1730
0
            return ret;
1731
0
        }
1732
0
    }
1733
1734
    /*
1735
     * Determine the key exchange algorithm to use.
1736
     * There are three types of key exchanges supported in TLS 1.3:
1737
     * - (EC)DH with ECDSA,
1738
     * - (EC)DH with PSK,
1739
     * - plain PSK.
1740
     *
1741
     * The PSK-based key exchanges may additionally be used with 0-RTT.
1742
     *
1743
     * Our built-in order of preference is
1744
     *  1 ) (EC)DHE-PSK Mode ( psk_ephemeral )
1745
     *  2 ) Certificate Mode ( ephemeral )
1746
     *  3 ) Plain PSK Mode ( psk )
1747
     */
1748
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1749
0
    if (got_psk && (psk.key_exchange_mode ==
1750
0
                    MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL)) {
1751
0
        handshake->key_exchange_mode =
1752
0
            MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL;
1753
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk_ephemeral"));
1754
1755
0
    } else
1756
0
#endif
1757
0
    if (ssl_tls13_key_exchange_is_ephemeral_available(ssl)) {
1758
0
        handshake->key_exchange_mode =
1759
0
            MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL;
1760
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: ephemeral"));
1761
1762
0
    }
1763
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1764
0
    else if (got_psk && (psk.key_exchange_mode ==
1765
0
                         MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK)) {
1766
0
        handshake->key_exchange_mode = MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK;
1767
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("key exchange mode: psk"));
1768
0
    }
1769
0
#endif
1770
0
    else {
1771
0
        MBEDTLS_SSL_DEBUG_MSG(
1772
0
            1,
1773
0
            ("ClientHello message misses mandatory extensions."));
1774
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_MISSING_EXTENSION,
1775
0
                                     MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1776
0
        return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1777
0
    }
1778
1779
0
    if (handshake->key_exchange_mode !=
1780
0
        MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK) {
1781
0
        hrr_required = (no_usable_share_for_key_agreement != 0);
1782
0
    }
1783
1784
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
1785
0
    if (handshake->key_exchange_mode &
1786
0
        MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL) {
1787
0
        handshake->ciphersuite_info = psk.ciphersuite_info;
1788
0
        ssl->session_negotiate->ciphersuite = psk.ciphersuite_info->id;
1789
1790
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("Select PSK ciphersuite: %04x - %s",
1791
0
                                  ((unsigned) psk.ciphersuite_info->id),
1792
0
                                  psk.ciphersuite_info->name));
1793
1794
0
        if (psk.type == MBEDTLS_SSL_TLS1_3_PSK_RESUMPTION && (!hrr_required)) {
1795
0
            handshake->resume = 1;
1796
0
        }
1797
0
    }
1798
0
#endif
1799
1800
0
    mbedtls_ssl_optimize_checksum(ssl, handshake->ciphersuite_info);
1801
1802
0
    return hrr_required ? SSL_CLIENT_HELLO_HRR_REQUIRED : SSL_CLIENT_HELLO_OK;
1803
0
}
1804
1805
#if defined(MBEDTLS_SSL_EARLY_DATA)
1806
static int ssl_tls13_check_early_data_requirements(mbedtls_ssl_context *ssl)
1807
0
{
1808
0
    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
1809
1810
0
    if (ssl->conf->early_data_enabled == MBEDTLS_SSL_EARLY_DATA_DISABLED) {
1811
0
        MBEDTLS_SSL_DEBUG_MSG(
1812
0
            1,
1813
0
            ("EarlyData: rejected, feature disabled in server configuration."));
1814
0
        return -1;
1815
0
    }
1816
1817
0
    if (!handshake->resume) {
1818
        /* We currently support early data only in the case of PSKs established
1819
           via a NewSessionTicket message thus in the case of a session
1820
           resumption. */
1821
0
        MBEDTLS_SSL_DEBUG_MSG(
1822
0
            1, ("EarlyData: rejected, not a session resumption."));
1823
0
        return -1;
1824
0
    }
1825
1826
    /* RFC 8446 4.2.10
1827
     *
1828
     * In order to accept early data, the server MUST have accepted a PSK cipher
1829
     * suite and selected the first key offered in the client's "pre_shared_key"
1830
     * extension. In addition, it MUST verify that the following values are the
1831
     * same as those associated with the selected PSK:
1832
     * - The TLS version number
1833
     * - The selected cipher suite
1834
     * - The selected ALPN [RFC7301] protocol, if any
1835
     *
1836
     * NOTE:
1837
     *  - The TLS version number is checked in
1838
     *    ssl_tls13_offered_psks_check_identity_match_ticket().
1839
     */
1840
1841
0
    if (handshake->selected_identity != 0) {
1842
0
        MBEDTLS_SSL_DEBUG_MSG(
1843
0
            1, ("EarlyData: rejected, the selected key in "
1844
0
                "`pre_shared_key` is not the first one."));
1845
0
        return -1;
1846
0
    }
1847
1848
0
    if (handshake->ciphersuite_info->id !=
1849
0
        ssl->session_negotiate->ciphersuite) {
1850
0
        MBEDTLS_SSL_DEBUG_MSG(
1851
0
            1, ("EarlyData: rejected, the selected ciphersuite is not the one "
1852
0
                "of the selected pre-shared key."));
1853
0
        return -1;
1854
1855
0
    }
1856
1857
0
    if (!mbedtls_ssl_tls13_session_ticket_allow_early_data(ssl->session_negotiate)) {
1858
0
        MBEDTLS_SSL_DEBUG_MSG(
1859
0
            1,
1860
0
            ("EarlyData: rejected, early_data not allowed in ticket "
1861
0
             "permission bits."));
1862
0
        return -1;
1863
0
    }
1864
1865
0
#if defined(MBEDTLS_SSL_ALPN)
1866
0
    const char *alpn = mbedtls_ssl_get_alpn_protocol(ssl);
1867
0
    size_t alpn_len;
1868
1869
0
    if (alpn == NULL && ssl->session_negotiate->ticket_alpn == NULL) {
1870
0
        return 0;
1871
0
    }
1872
1873
0
    if (alpn != NULL) {
1874
0
        alpn_len = strlen(alpn);
1875
0
    }
1876
1877
0
    if (alpn == NULL ||
1878
0
        ssl->session_negotiate->ticket_alpn == NULL ||
1879
0
        alpn_len != strlen(ssl->session_negotiate->ticket_alpn) ||
1880
0
        (memcmp(alpn, ssl->session_negotiate->ticket_alpn, alpn_len) != 0)) {
1881
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("EarlyData: rejected, the selected ALPN is different "
1882
0
                                  "from the one associated with the pre-shared key."));
1883
0
        return -1;
1884
0
    }
1885
0
#endif
1886
1887
0
    return 0;
1888
0
}
1889
#endif /* MBEDTLS_SSL_EARLY_DATA */
1890
1891
/* Update the handshake state machine */
1892
1893
MBEDTLS_CHECK_RETURN_CRITICAL
1894
static int ssl_tls13_postprocess_client_hello(mbedtls_ssl_context *ssl,
1895
                                              int hrr_required)
1896
0
{
1897
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1898
1899
    /*
1900
     * Server certificate selection
1901
     */
1902
0
    if (ssl->conf->f_cert_cb && (ret = ssl->conf->f_cert_cb(ssl)) != 0) {
1903
0
        MBEDTLS_SSL_DEBUG_RET(1, "f_cert_cb", ret);
1904
0
        return ret;
1905
0
    }
1906
0
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
1907
0
    ssl->handshake->sni_name = NULL;
1908
0
    ssl->handshake->sni_name_len = 0;
1909
0
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
1910
1911
0
    ret = mbedtls_ssl_tls13_key_schedule_stage_early(ssl);
1912
0
    if (ret != 0) {
1913
0
        MBEDTLS_SSL_DEBUG_RET(1,
1914
0
                              "mbedtls_ssl_tls1_3_key_schedule_stage_early", ret);
1915
0
        return ret;
1916
0
    }
1917
1918
0
#if defined(MBEDTLS_SSL_EARLY_DATA)
1919
0
    if (ssl->handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(EARLY_DATA)) {
1920
0
        ssl->handshake->early_data_accepted =
1921
0
            (!hrr_required) && (ssl_tls13_check_early_data_requirements(ssl) == 0);
1922
1923
0
        if (ssl->handshake->early_data_accepted) {
1924
0
            ret = mbedtls_ssl_tls13_compute_early_transform(ssl);
1925
0
            if (ret != 0) {
1926
0
                MBEDTLS_SSL_DEBUG_RET(
1927
0
                    1, "mbedtls_ssl_tls13_compute_early_transform", ret);
1928
0
                return ret;
1929
0
            }
1930
0
        } else {
1931
0
            ssl->discard_early_data_record =
1932
0
                hrr_required ?
1933
0
                MBEDTLS_SSL_EARLY_DATA_DISCARD :
1934
0
                MBEDTLS_SSL_EARLY_DATA_TRY_TO_DEPROTECT_AND_DISCARD;
1935
0
        }
1936
0
    }
1937
#else
1938
    ((void) hrr_required);
1939
#endif /* MBEDTLS_SSL_EARLY_DATA */
1940
1941
0
    return 0;
1942
0
}
1943
1944
/*
1945
 * Main entry point from the state machine; orchestrates the otherfunctions.
1946
 */
1947
1948
MBEDTLS_CHECK_RETURN_CRITICAL
1949
static int ssl_tls13_process_client_hello(mbedtls_ssl_context *ssl)
1950
1.84k
{
1951
1952
1.84k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1953
1.84k
    unsigned char *buf = NULL;
1954
1.84k
    size_t buflen = 0;
1955
1.84k
    int parse_client_hello_ret;
1956
1957
1.84k
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse client hello"));
1958
1959
1.84k
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
1960
1.84k
                             ssl, MBEDTLS_SSL_HS_CLIENT_HELLO,
1961
1.84k
                             &buf, &buflen));
1962
1963
1.45k
    MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_parse_client_hello(ssl, buf,
1964
1.45k
                                                          buf + buflen));
1965
1.28k
    parse_client_hello_ret = ret; /* Store positive return value of
1966
                                   * parse_client_hello,
1967
                                   * as negative error codes are handled
1968
                                   * by MBEDTLS_SSL_PROC_CHK_NEG. */
1969
1970
    /*
1971
     * Version 1.2 of the protocol has to be used for the handshake.
1972
     * If we have sent an HRR, then the second ClientHello is inconsistent
1973
     * with the first one and we abort the handshake with an `illegal_parameter`
1974
     * fatal alert.
1975
     * If TLS 1.2 is not supported, abort the handshake. Otherwise, set the
1976
     * ssl->keep_current_message flag for the ClientHello to be kept and parsed
1977
     * as a TLS 1.2 ClientHello. We also change ssl->tls_version to
1978
     * MBEDTLS_SSL_VERSION_TLS1_2 thus from now on mbedtls_ssl_handshake_step()
1979
     * will dispatch to the TLS 1.2 state machine.
1980
     */
1981
1.28k
    if (SSL_CLIENT_HELLO_TLS1_2 == parse_client_hello_ret) {
1982
1.28k
        if (ssl->handshake->hello_retry_request_flag) {
1983
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("Non compliant 2nd ClientHello, TLS 1.2 version"));
1984
0
            MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER,
1985
0
                                         MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER);
1986
0
            return MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER;
1987
0
        }
1988
1.28k
        if (!mbedtls_ssl_conf_is_tls12_enabled(ssl->conf)) {
1989
0
            MBEDTLS_SSL_DEBUG_MSG(
1990
0
                1, ("TLS 1.2 not supported."));
1991
0
            MBEDTLS_SSL_PEND_FATAL_ALERT(
1992
0
                MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION,
1993
0
                MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION);
1994
0
            return MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION;
1995
0
        }
1996
1.28k
        ssl->keep_current_message = 1;
1997
1.28k
        ssl->tls_version = MBEDTLS_SSL_VERSION_TLS1_2;
1998
1.28k
        MBEDTLS_SSL_DEBUG_MSG(1, ("non-1.3 ClientHello left for later processing"));
1999
1.28k
        return 0;
2000
1.28k
    }
2001
2002
0
    MBEDTLS_SSL_PROC_CHK(
2003
0
        ssl_tls13_postprocess_client_hello(ssl, parse_client_hello_ret ==
2004
0
                                           SSL_CLIENT_HELLO_HRR_REQUIRED));
2005
2006
0
    if (SSL_CLIENT_HELLO_OK == parse_client_hello_ret) {
2007
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_HELLO);
2008
0
    } else {
2009
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HELLO_RETRY_REQUEST);
2010
0
    }
2011
2012
560
cleanup:
2013
2014
560
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse client hello"));
2015
560
    return ret;
2016
0
}
2017
2018
/*
2019
 * Handler for MBEDTLS_SSL_SERVER_HELLO
2020
 */
2021
MBEDTLS_CHECK_RETURN_CRITICAL
2022
static int ssl_tls13_prepare_server_hello(mbedtls_ssl_context *ssl)
2023
0
{
2024
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2025
0
    unsigned char *server_randbytes =
2026
0
        ssl->handshake->randbytes + MBEDTLS_CLIENT_HELLO_RANDOM_LEN;
2027
2028
0
    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng, server_randbytes,
2029
0
                                MBEDTLS_SERVER_HELLO_RANDOM_LEN)) != 0) {
2030
0
        MBEDTLS_SSL_DEBUG_RET(1, "f_rng", ret);
2031
0
        return ret;
2032
0
    }
2033
2034
0
    MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes", server_randbytes,
2035
0
                          MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2036
2037
0
#if defined(MBEDTLS_HAVE_TIME)
2038
0
    ssl->session_negotiate->start = mbedtls_time(NULL);
2039
0
#endif /* MBEDTLS_HAVE_TIME */
2040
2041
0
    return ret;
2042
0
}
2043
2044
/*
2045
 * ssl_tls13_write_server_hello_supported_versions_ext ():
2046
 *
2047
 * struct {
2048
 *      ProtocolVersion selected_version;
2049
 * } SupportedVersions;
2050
 */
2051
MBEDTLS_CHECK_RETURN_CRITICAL
2052
static int ssl_tls13_write_server_hello_supported_versions_ext(
2053
    mbedtls_ssl_context *ssl,
2054
    unsigned char *buf,
2055
    unsigned char *end,
2056
    size_t *out_len)
2057
0
{
2058
0
    *out_len = 0;
2059
2060
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, write selected version"));
2061
2062
    /* Check if we have space to write the extension:
2063
     * - extension_type         (2 bytes)
2064
     * - extension_data_length  (2 bytes)
2065
     * - selected_version       (2 bytes)
2066
     */
2067
0
    MBEDTLS_SSL_CHK_BUF_PTR(buf, end, 6);
2068
2069
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS, buf, 0);
2070
2071
0
    MBEDTLS_PUT_UINT16_BE(2, buf, 2);
2072
2073
0
    mbedtls_ssl_write_version(buf + 4,
2074
0
                              ssl->conf->transport,
2075
0
                              ssl->tls_version);
2076
2077
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("supported version: [%04x]",
2078
0
                              ssl->tls_version));
2079
2080
0
    *out_len = 6;
2081
2082
0
    mbedtls_ssl_tls13_set_hs_sent_ext_mask(
2083
0
        ssl, MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS);
2084
2085
0
    return 0;
2086
0
}
2087
2088
2089
2090
/* Generate and export a single key share. For hybrid KEMs, this can
2091
 * be called multiple times with the different components of the hybrid. */
2092
MBEDTLS_CHECK_RETURN_CRITICAL
2093
static int ssl_tls13_generate_and_write_key_share(mbedtls_ssl_context *ssl,
2094
                                                  uint16_t named_group,
2095
                                                  unsigned char *buf,
2096
                                                  unsigned char *end,
2097
                                                  size_t *out_len)
2098
0
{
2099
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2100
2101
0
    *out_len = 0;
2102
2103
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
2104
0
    if (mbedtls_ssl_tls13_named_group_is_ecdhe(named_group) ||
2105
0
        mbedtls_ssl_tls13_named_group_is_ffdh(named_group)) {
2106
0
        ret = mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange(
2107
0
            ssl, named_group, buf, end, out_len);
2108
0
        if (ret != 0) {
2109
0
            MBEDTLS_SSL_DEBUG_RET(
2110
0
                1, "mbedtls_ssl_tls13_generate_and_write_xxdh_key_exchange",
2111
0
                ret);
2112
0
            return ret;
2113
0
        }
2114
0
    } else
2115
0
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED */
2116
0
    if (0 /* Other kinds of KEMs */) {
2117
0
    } else {
2118
0
        ((void) ssl);
2119
0
        ((void) named_group);
2120
0
        ((void) buf);
2121
0
        ((void) end);
2122
0
        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2123
0
    }
2124
2125
0
    return ret;
2126
0
}
2127
2128
/*
2129
 * ssl_tls13_write_key_share_ext
2130
 *
2131
 * Structure of key_share extension in ServerHello:
2132
 *
2133
 * struct {
2134
 *     NamedGroup group;
2135
 *     opaque key_exchange<1..2^16-1>;
2136
 * } KeyShareEntry;
2137
 * struct {
2138
 *     KeyShareEntry server_share;
2139
 * } KeyShareServerHello;
2140
 */
2141
MBEDTLS_CHECK_RETURN_CRITICAL
2142
static int ssl_tls13_write_key_share_ext(mbedtls_ssl_context *ssl,
2143
                                         unsigned char *buf,
2144
                                         unsigned char *end,
2145
                                         size_t *out_len)
2146
0
{
2147
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2148
0
    unsigned char *p = buf;
2149
0
    uint16_t group = ssl->handshake->offered_group_id;
2150
0
    unsigned char *server_share = buf + 4;
2151
0
    size_t key_exchange_length;
2152
2153
0
    *out_len = 0;
2154
2155
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("server hello, adding key share extension"));
2156
2157
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("server hello, write selected_group: %s (%04x)",
2158
0
                              mbedtls_ssl_named_group_to_str(group),
2159
0
                              group));
2160
2161
    /* Check if we have space for header and length fields:
2162
     * - extension_type         (2 bytes)
2163
     * - extension_data_length  (2 bytes)
2164
     * - group                  (2 bytes)
2165
     * - key_exchange_length    (2 bytes)
2166
     */
2167
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 8);
2168
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_KEY_SHARE, p, 0);
2169
0
    MBEDTLS_PUT_UINT16_BE(group, server_share, 0);
2170
0
    p += 8;
2171
2172
    /* When we introduce PQC-ECDHE hybrids, we'll want to call this
2173
     * function multiple times. */
2174
0
    ret = ssl_tls13_generate_and_write_key_share(
2175
0
        ssl, group, server_share + 4, end, &key_exchange_length);
2176
0
    if (ret != 0) {
2177
0
        return ret;
2178
0
    }
2179
0
    p += key_exchange_length;
2180
2181
0
    MBEDTLS_PUT_UINT16_BE(key_exchange_length, server_share + 2, 0);
2182
2183
0
    MBEDTLS_PUT_UINT16_BE(p - server_share, buf, 2);
2184
2185
0
    *out_len = p - buf;
2186
2187
0
    mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_KEY_SHARE);
2188
2189
0
    return 0;
2190
0
}
2191
2192
MBEDTLS_CHECK_RETURN_CRITICAL
2193
static int ssl_tls13_write_hrr_key_share_ext(mbedtls_ssl_context *ssl,
2194
                                             unsigned char *buf,
2195
                                             unsigned char *end,
2196
                                             size_t *out_len)
2197
0
{
2198
0
    uint16_t selected_group = ssl->handshake->hrr_selected_group;
2199
    /* key_share Extension
2200
     *
2201
     *  struct {
2202
     *    select (Handshake.msg_type) {
2203
     *      ...
2204
     *      case hello_retry_request:
2205
     *          NamedGroup selected_group;
2206
     *      ...
2207
     *    };
2208
     * } KeyShare;
2209
     */
2210
2211
0
    *out_len = 0;
2212
2213
    /*
2214
     * For a pure PSK key exchange, there is no group to agree upon. The purpose
2215
     * of the HRR is then to transmit a cookie to force the client to demonstrate
2216
     * reachability at their apparent network address (primarily useful for DTLS).
2217
     */
2218
0
    if (!mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(ssl)) {
2219
0
        return 0;
2220
0
    }
2221
2222
    /* We should only send the key_share extension if the client's initial
2223
     * key share was not acceptable. */
2224
0
    if (ssl->handshake->offered_group_id != 0) {
2225
0
        MBEDTLS_SSL_DEBUG_MSG(4, ("Skip key_share extension in HRR"));
2226
0
        return 0;
2227
0
    }
2228
2229
0
    if (selected_group == 0) {
2230
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("no matching named group found"));
2231
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2232
0
    }
2233
2234
    /* Check if we have enough space:
2235
     * - extension_type         (2 bytes)
2236
     * - extension_data_length  (2 bytes)
2237
     * - selected_group         (2 bytes)
2238
     */
2239
0
    MBEDTLS_SSL_CHK_BUF_PTR(buf, end, 6);
2240
2241
0
    MBEDTLS_PUT_UINT16_BE(MBEDTLS_TLS_EXT_KEY_SHARE, buf, 0);
2242
0
    MBEDTLS_PUT_UINT16_BE(2, buf, 2);
2243
0
    MBEDTLS_PUT_UINT16_BE(selected_group, buf, 4);
2244
2245
0
    MBEDTLS_SSL_DEBUG_MSG(3,
2246
0
                          ("HRR selected_group: %s (%x)",
2247
0
                           mbedtls_ssl_named_group_to_str(selected_group),
2248
0
                           selected_group));
2249
2250
0
    *out_len = 6;
2251
2252
0
    mbedtls_ssl_tls13_set_hs_sent_ext_mask(ssl, MBEDTLS_TLS_EXT_KEY_SHARE);
2253
2254
0
    return 0;
2255
0
}
2256
2257
/*
2258
 * Structure of ServerHello message:
2259
 *
2260
 *     struct {
2261
 *        ProtocolVersion legacy_version = 0x0303;    // TLS v1.2
2262
 *        Random random;
2263
 *        opaque legacy_session_id_echo<0..32>;
2264
 *        CipherSuite cipher_suite;
2265
 *        uint8 legacy_compression_method = 0;
2266
 *        Extension extensions<6..2^16-1>;
2267
 *    } ServerHello;
2268
 */
2269
MBEDTLS_CHECK_RETURN_CRITICAL
2270
static int ssl_tls13_write_server_hello_body(mbedtls_ssl_context *ssl,
2271
                                             unsigned char *buf,
2272
                                             unsigned char *end,
2273
                                             size_t *out_len,
2274
                                             int is_hrr)
2275
0
{
2276
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2277
0
    unsigned char *p = buf;
2278
0
    unsigned char *p_extensions_len;
2279
0
    size_t output_len;
2280
2281
0
    *out_len = 0;
2282
0
    ssl->handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
2283
2284
    /* ...
2285
     * ProtocolVersion legacy_version = 0x0303; // TLS 1.2
2286
     * ...
2287
     * with ProtocolVersion defined as:
2288
     * uint16 ProtocolVersion;
2289
     */
2290
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2291
0
    MBEDTLS_PUT_UINT16_BE(0x0303, p, 0);
2292
0
    p += 2;
2293
2294
    /* ...
2295
     * Random random;
2296
     * ...
2297
     * with Random defined as:
2298
     * opaque Random[MBEDTLS_SERVER_HELLO_RANDOM_LEN];
2299
     */
2300
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2301
0
    if (is_hrr) {
2302
0
        memcpy(p, mbedtls_ssl_tls13_hello_retry_request_magic,
2303
0
               MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2304
0
    } else {
2305
0
        memcpy(p, &ssl->handshake->randbytes[MBEDTLS_CLIENT_HELLO_RANDOM_LEN],
2306
0
               MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2307
0
    }
2308
0
    MBEDTLS_SSL_DEBUG_BUF(3, "server hello, random bytes",
2309
0
                          p, MBEDTLS_SERVER_HELLO_RANDOM_LEN);
2310
0
    p += MBEDTLS_SERVER_HELLO_RANDOM_LEN;
2311
2312
    /* ...
2313
     * opaque legacy_session_id_echo<0..32>;
2314
     * ...
2315
     */
2316
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 1 + ssl->session_negotiate->id_len);
2317
0
    *p++ = (unsigned char) ssl->session_negotiate->id_len;
2318
0
    if (ssl->session_negotiate->id_len > 0) {
2319
0
        memcpy(p, &ssl->session_negotiate->id[0],
2320
0
               ssl->session_negotiate->id_len);
2321
0
        p += ssl->session_negotiate->id_len;
2322
2323
0
        MBEDTLS_SSL_DEBUG_BUF(3, "session id", ssl->session_negotiate->id,
2324
0
                              ssl->session_negotiate->id_len);
2325
0
    }
2326
2327
    /* ...
2328
     * CipherSuite cipher_suite;
2329
     * ...
2330
     * with CipherSuite defined as:
2331
     * uint8 CipherSuite[2];
2332
     */
2333
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2334
0
    MBEDTLS_PUT_UINT16_BE(ssl->session_negotiate->ciphersuite, p, 0);
2335
0
    p += 2;
2336
0
    MBEDTLS_SSL_DEBUG_MSG(3,
2337
0
                          ("server hello, chosen ciphersuite: %s ( id=%d )",
2338
0
                           mbedtls_ssl_get_ciphersuite_name(
2339
0
                               ssl->session_negotiate->ciphersuite),
2340
0
                           ssl->session_negotiate->ciphersuite));
2341
2342
    /* ...
2343
     * uint8 legacy_compression_method = 0;
2344
     * ...
2345
     */
2346
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 1);
2347
0
    *p++ = MBEDTLS_SSL_COMPRESS_NULL;
2348
2349
    /* ...
2350
     * Extension extensions<6..2^16-1>;
2351
     * ...
2352
     * struct {
2353
     *      ExtensionType extension_type; (2 bytes)
2354
     *      opaque extension_data<0..2^16-1>;
2355
     * } Extension;
2356
     */
2357
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2358
0
    p_extensions_len = p;
2359
0
    p += 2;
2360
2361
0
    if ((ret = ssl_tls13_write_server_hello_supported_versions_ext(
2362
0
             ssl, p, end, &output_len)) != 0) {
2363
0
        MBEDTLS_SSL_DEBUG_RET(
2364
0
            1, "ssl_tls13_write_server_hello_supported_versions_ext", ret);
2365
0
        return ret;
2366
0
    }
2367
0
    p += output_len;
2368
2369
0
    if (mbedtls_ssl_tls13_key_exchange_mode_with_ephemeral(ssl)) {
2370
0
        if (is_hrr) {
2371
0
            ret = ssl_tls13_write_hrr_key_share_ext(ssl, p, end, &output_len);
2372
0
        } else {
2373
0
            ret = ssl_tls13_write_key_share_ext(ssl, p, end, &output_len);
2374
0
        }
2375
0
        if (ret != 0) {
2376
0
            return ret;
2377
0
        }
2378
0
        p += output_len;
2379
0
    }
2380
2381
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
2382
0
    if (!is_hrr && mbedtls_ssl_tls13_key_exchange_mode_with_psk(ssl)) {
2383
0
        ret = ssl_tls13_write_server_pre_shared_key_ext(ssl, p, end, &output_len);
2384
0
        if (ret != 0) {
2385
0
            MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_write_server_pre_shared_key_ext",
2386
0
                                  ret);
2387
0
            return ret;
2388
0
        }
2389
0
        p += output_len;
2390
0
    }
2391
0
#endif
2392
2393
0
    MBEDTLS_PUT_UINT16_BE(p - p_extensions_len - 2, p_extensions_len, 0);
2394
2395
0
    MBEDTLS_SSL_DEBUG_BUF(4, "server hello extensions",
2396
0
                          p_extensions_len, p - p_extensions_len);
2397
2398
0
    *out_len = p - buf;
2399
2400
0
    MBEDTLS_SSL_DEBUG_BUF(3, "server hello", buf, *out_len);
2401
2402
0
    MBEDTLS_SSL_PRINT_EXTS(
2403
0
        3, is_hrr ? MBEDTLS_SSL_TLS1_3_HS_HELLO_RETRY_REQUEST :
2404
0
        MBEDTLS_SSL_HS_SERVER_HELLO,
2405
0
        ssl->handshake->sent_extensions);
2406
2407
0
    return ret;
2408
0
}
2409
2410
MBEDTLS_CHECK_RETURN_CRITICAL
2411
static int ssl_tls13_finalize_server_hello(mbedtls_ssl_context *ssl)
2412
0
{
2413
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2414
0
    ret = mbedtls_ssl_tls13_compute_handshake_transform(ssl);
2415
0
    if (ret != 0) {
2416
0
        MBEDTLS_SSL_DEBUG_RET(1,
2417
0
                              "mbedtls_ssl_tls13_compute_handshake_transform",
2418
0
                              ret);
2419
0
        return ret;
2420
0
    }
2421
2422
0
    return ret;
2423
0
}
2424
2425
MBEDTLS_CHECK_RETURN_CRITICAL
2426
static int ssl_tls13_write_server_hello(mbedtls_ssl_context *ssl)
2427
0
{
2428
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2429
0
    unsigned char *buf;
2430
0
    size_t buf_len, msg_len;
2431
2432
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write server hello"));
2433
2434
0
    MBEDTLS_SSL_PROC_CHK(ssl_tls13_prepare_server_hello(ssl));
2435
2436
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2437
0
                             ssl, MBEDTLS_SSL_HS_SERVER_HELLO, &buf, &buf_len));
2438
2439
0
    MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_server_hello_body(ssl, buf,
2440
0
                                                           buf + buf_len,
2441
0
                                                           &msg_len,
2442
0
                                                           0));
2443
2444
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2445
0
                             ssl, MBEDTLS_SSL_HS_SERVER_HELLO, buf, msg_len));
2446
2447
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
2448
0
                             ssl, buf_len, msg_len));
2449
2450
0
    MBEDTLS_SSL_PROC_CHK(ssl_tls13_finalize_server_hello(ssl));
2451
2452
0
#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
2453
    /* The server sends a dummy change_cipher_spec record immediately
2454
     * after its first handshake message. This may either be after
2455
     * a ServerHello or a HelloRetryRequest.
2456
     */
2457
0
    mbedtls_ssl_handshake_set_state(
2458
0
        ssl, MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO);
2459
#else
2460
    mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
2461
#endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
2462
2463
0
cleanup:
2464
2465
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write server hello"));
2466
0
    return ret;
2467
0
}
2468
2469
2470
/*
2471
 * Handler for MBEDTLS_SSL_HELLO_RETRY_REQUEST
2472
 */
2473
MBEDTLS_CHECK_RETURN_CRITICAL
2474
static int ssl_tls13_prepare_hello_retry_request(mbedtls_ssl_context *ssl)
2475
0
{
2476
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2477
0
    if (ssl->handshake->hello_retry_request_flag) {
2478
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("Too many HRRs"));
2479
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
2480
0
                                     MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
2481
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2482
0
    }
2483
2484
    /*
2485
     * Create stateless transcript hash for HRR
2486
     */
2487
0
    MBEDTLS_SSL_DEBUG_MSG(4, ("Reset transcript for HRR"));
2488
0
    ret = mbedtls_ssl_reset_transcript_for_hrr(ssl);
2489
0
    if (ret != 0) {
2490
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_reset_transcript_for_hrr", ret);
2491
0
        return ret;
2492
0
    }
2493
0
    mbedtls_ssl_session_reset_msg_layer(ssl, 0);
2494
2495
0
    return 0;
2496
0
}
2497
2498
MBEDTLS_CHECK_RETURN_CRITICAL
2499
static int ssl_tls13_write_hello_retry_request(mbedtls_ssl_context *ssl)
2500
0
{
2501
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2502
0
    unsigned char *buf;
2503
0
    size_t buf_len, msg_len;
2504
2505
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write hello retry request"));
2506
2507
0
    MBEDTLS_SSL_PROC_CHK(ssl_tls13_prepare_hello_retry_request(ssl));
2508
2509
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2510
0
                             ssl, MBEDTLS_SSL_HS_SERVER_HELLO,
2511
0
                             &buf, &buf_len));
2512
2513
0
    MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_server_hello_body(ssl, buf,
2514
0
                                                           buf + buf_len,
2515
0
                                                           &msg_len,
2516
0
                                                           1));
2517
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2518
0
                             ssl, MBEDTLS_SSL_HS_SERVER_HELLO, buf, msg_len));
2519
2520
2521
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(ssl, buf_len,
2522
0
                                                          msg_len));
2523
2524
0
    ssl->handshake->hello_retry_request_flag = 1;
2525
2526
0
#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
2527
    /* The server sends a dummy change_cipher_spec record immediately
2528
     * after its first handshake message. This may either be after
2529
     * a ServerHello or a HelloRetryRequest.
2530
     */
2531
0
    mbedtls_ssl_handshake_set_state(
2532
0
        ssl, MBEDTLS_SSL_SERVER_CCS_AFTER_HELLO_RETRY_REQUEST);
2533
#else
2534
    mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
2535
#endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
2536
2537
0
cleanup:
2538
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write hello retry request"));
2539
0
    return ret;
2540
0
}
2541
2542
/*
2543
 * Handler for MBEDTLS_SSL_ENCRYPTED_EXTENSIONS
2544
 */
2545
2546
/*
2547
 * struct {
2548
 *    Extension extensions<0..2 ^ 16 - 1>;
2549
 * } EncryptedExtensions;
2550
 *
2551
 */
2552
MBEDTLS_CHECK_RETURN_CRITICAL
2553
static int ssl_tls13_write_encrypted_extensions_body(mbedtls_ssl_context *ssl,
2554
                                                     unsigned char *buf,
2555
                                                     unsigned char *end,
2556
                                                     size_t *out_len)
2557
0
{
2558
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2559
0
    unsigned char *p = buf;
2560
0
    size_t extensions_len = 0;
2561
0
    unsigned char *p_extensions_len;
2562
0
    size_t output_len;
2563
2564
0
    *out_len = 0;
2565
2566
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
2567
0
    p_extensions_len = p;
2568
0
    p += 2;
2569
2570
0
    ((void) ssl);
2571
0
    ((void) ret);
2572
0
    ((void) output_len);
2573
2574
0
#if defined(MBEDTLS_SSL_ALPN)
2575
0
    ret = mbedtls_ssl_write_alpn_ext(ssl, p, end, &output_len);
2576
0
    if (ret != 0) {
2577
0
        return ret;
2578
0
    }
2579
0
    p += output_len;
2580
0
#endif /* MBEDTLS_SSL_ALPN */
2581
2582
0
#if defined(MBEDTLS_SSL_EARLY_DATA)
2583
0
    if (ssl->handshake->early_data_accepted) {
2584
0
        ret = mbedtls_ssl_tls13_write_early_data_ext(
2585
0
            ssl, 0, p, end, &output_len);
2586
0
        if (ret != 0) {
2587
0
            return ret;
2588
0
        }
2589
0
        p += output_len;
2590
0
    }
2591
0
#endif /* MBEDTLS_SSL_EARLY_DATA */
2592
2593
0
#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT)
2594
0
    if (ssl->handshake->received_extensions & MBEDTLS_SSL_EXT_MASK(RECORD_SIZE_LIMIT)) {
2595
0
        ret = mbedtls_ssl_tls13_write_record_size_limit_ext(
2596
0
            ssl, p, end, &output_len);
2597
0
        if (ret != 0) {
2598
0
            return ret;
2599
0
        }
2600
0
        p += output_len;
2601
0
    }
2602
0
#endif
2603
2604
0
    extensions_len = (p - p_extensions_len) - 2;
2605
0
    MBEDTLS_PUT_UINT16_BE(extensions_len, p_extensions_len, 0);
2606
2607
0
    *out_len = p - buf;
2608
2609
0
    MBEDTLS_SSL_DEBUG_BUF(4, "encrypted extensions", buf, *out_len);
2610
2611
0
    MBEDTLS_SSL_PRINT_EXTS(
2612
0
        3, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS, ssl->handshake->sent_extensions);
2613
2614
0
    return 0;
2615
0
}
2616
2617
MBEDTLS_CHECK_RETURN_CRITICAL
2618
static int ssl_tls13_write_encrypted_extensions(mbedtls_ssl_context *ssl)
2619
0
{
2620
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2621
0
    unsigned char *buf;
2622
0
    size_t buf_len, msg_len;
2623
2624
0
    mbedtls_ssl_set_outbound_transform(ssl,
2625
0
                                       ssl->handshake->transform_handshake);
2626
0
    MBEDTLS_SSL_DEBUG_MSG(
2627
0
        3, ("switching to handshake transform for outbound data"));
2628
2629
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write encrypted extensions"));
2630
2631
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2632
0
                             ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2633
0
                             &buf, &buf_len));
2634
2635
0
    MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_encrypted_extensions_body(
2636
0
                             ssl, buf, buf + buf_len, &msg_len));
2637
2638
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2639
0
                             ssl, MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS,
2640
0
                             buf, msg_len));
2641
2642
0
    MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
2643
0
                             ssl, buf_len, msg_len));
2644
2645
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2646
0
    if (mbedtls_ssl_tls13_key_exchange_mode_with_psk(ssl)) {
2647
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2648
2649
        /* Since we're not using a certificate, set verify_result to success */
2650
0
        ssl->session_negotiate->verify_result = 0;
2651
0
    } else {
2652
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CERTIFICATE_REQUEST);
2653
0
    }
2654
#else
2655
    mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2656
#endif
2657
2658
0
cleanup:
2659
2660
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write encrypted extensions"));
2661
0
    return ret;
2662
0
}
2663
2664
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
2665
0
#define SSL_CERTIFICATE_REQUEST_SEND_REQUEST 0
2666
0
#define SSL_CERTIFICATE_REQUEST_SKIP         1
2667
/* Coordination:
2668
 * Check whether a CertificateRequest message should be written.
2669
 * Returns a negative code on failure, or
2670
 * - SSL_CERTIFICATE_REQUEST_SEND_REQUEST
2671
 * - SSL_CERTIFICATE_REQUEST_SKIP
2672
 * indicating if the writing of the CertificateRequest
2673
 * should be skipped or not.
2674
 */
2675
MBEDTLS_CHECK_RETURN_CRITICAL
2676
static int ssl_tls13_certificate_request_coordinate(mbedtls_ssl_context *ssl)
2677
0
{
2678
0
    int authmode;
2679
2680
0
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2681
0
    if (ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET) {
2682
0
        authmode = ssl->handshake->sni_authmode;
2683
0
    } else
2684
0
#endif
2685
0
    authmode = ssl->conf->authmode;
2686
2687
0
    if (authmode == MBEDTLS_SSL_VERIFY_NONE) {
2688
0
        ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_SKIP_VERIFY;
2689
0
        return SSL_CERTIFICATE_REQUEST_SKIP;
2690
0
    }
2691
2692
0
    ssl->handshake->certificate_request_sent = 1;
2693
2694
0
    return SSL_CERTIFICATE_REQUEST_SEND_REQUEST;
2695
0
}
2696
2697
/*
2698
 * struct {
2699
 *   opaque certificate_request_context<0..2^8-1>;
2700
 *   Extension extensions<2..2^16-1>;
2701
 * } CertificateRequest;
2702
 *
2703
 */
2704
MBEDTLS_CHECK_RETURN_CRITICAL
2705
static int ssl_tls13_write_certificate_request_body(mbedtls_ssl_context *ssl,
2706
                                                    unsigned char *buf,
2707
                                                    const unsigned char *end,
2708
                                                    size_t *out_len)
2709
0
{
2710
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2711
0
    unsigned char *p = buf;
2712
0
    size_t output_len = 0;
2713
0
    unsigned char *p_extensions_len;
2714
2715
0
    *out_len = 0;
2716
2717
    /* Check if we have enough space:
2718
     * - certificate_request_context (1 byte)
2719
     * - extensions length           (2 bytes)
2720
     */
2721
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 3);
2722
2723
    /*
2724
     * Write certificate_request_context
2725
     */
2726
    /*
2727
     * We use a zero length context for the normal handshake
2728
     * messages. For post-authentication handshake messages
2729
     * this request context would be set to a non-zero value.
2730
     */
2731
0
    *p++ = 0x0;
2732
2733
    /*
2734
     * Write extensions
2735
     */
2736
    /* The extensions must contain the signature_algorithms. */
2737
0
    p_extensions_len = p;
2738
0
    p += 2;
2739
0
    ret = mbedtls_ssl_write_sig_alg_ext(ssl, p, end, &output_len);
2740
0
    if (ret != 0) {
2741
0
        return ret;
2742
0
    }
2743
2744
0
    p += output_len;
2745
0
    MBEDTLS_PUT_UINT16_BE(p - p_extensions_len - 2, p_extensions_len, 0);
2746
2747
0
    *out_len = p - buf;
2748
2749
0
    MBEDTLS_SSL_PRINT_EXTS(
2750
0
        3, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST, ssl->handshake->sent_extensions);
2751
2752
0
    return 0;
2753
0
}
2754
2755
MBEDTLS_CHECK_RETURN_CRITICAL
2756
static int ssl_tls13_write_certificate_request(mbedtls_ssl_context *ssl)
2757
0
{
2758
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2759
2760
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate request"));
2761
2762
0
    MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_certificate_request_coordinate(ssl));
2763
2764
0
    if (ret == SSL_CERTIFICATE_REQUEST_SEND_REQUEST) {
2765
0
        unsigned char *buf;
2766
0
        size_t buf_len, msg_len;
2767
2768
0
        MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
2769
0
                                 ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2770
0
                                 &buf, &buf_len));
2771
2772
0
        MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_certificate_request_body(
2773
0
                                 ssl, buf, buf + buf_len, &msg_len));
2774
2775
0
        MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
2776
0
                                 ssl, MBEDTLS_SSL_HS_CERTIFICATE_REQUEST,
2777
0
                                 buf, msg_len));
2778
2779
0
        MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
2780
0
                                 ssl, buf_len, msg_len));
2781
0
    } else if (ret == SSL_CERTIFICATE_REQUEST_SKIP) {
2782
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate request"));
2783
0
        ret = 0;
2784
0
    } else {
2785
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2786
0
        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2787
0
        goto cleanup;
2788
0
    }
2789
2790
0
    mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_CERTIFICATE);
2791
0
cleanup:
2792
2793
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate request"));
2794
0
    return ret;
2795
0
}
2796
2797
/*
2798
 * Handler for MBEDTLS_SSL_SERVER_CERTIFICATE
2799
 */
2800
MBEDTLS_CHECK_RETURN_CRITICAL
2801
static int ssl_tls13_write_server_certificate(mbedtls_ssl_context *ssl)
2802
0
{
2803
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2804
2805
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
2806
0
    if ((ssl_tls13_pick_key_cert(ssl) != 0) ||
2807
0
        mbedtls_ssl_own_cert(ssl) == NULL) {
2808
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("No certificate available."));
2809
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
2810
0
                                     MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
2811
0
        return MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE;
2812
0
    }
2813
0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
2814
2815
0
    ret = mbedtls_ssl_tls13_write_certificate(ssl);
2816
0
    if (ret != 0) {
2817
0
        return ret;
2818
0
    }
2819
0
    mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CERTIFICATE_VERIFY);
2820
0
    return 0;
2821
0
}
2822
2823
/*
2824
 * Handler for MBEDTLS_SSL_CERTIFICATE_VERIFY
2825
 */
2826
MBEDTLS_CHECK_RETURN_CRITICAL
2827
static int ssl_tls13_write_certificate_verify(mbedtls_ssl_context *ssl)
2828
0
{
2829
0
    int ret = mbedtls_ssl_tls13_write_certificate_verify(ssl);
2830
0
    if (ret != 0) {
2831
0
        return ret;
2832
0
    }
2833
0
    mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_SERVER_FINISHED);
2834
0
    return 0;
2835
0
}
2836
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
2837
2838
/*
2839
 * RFC 8446 section A.2
2840
 *
2841
 *                                | Send ServerHello
2842
 *                                | K_send = handshake
2843
 *                                | Send EncryptedExtensions
2844
 *                                | [Send CertificateRequest]
2845
 * Can send                       | [Send Certificate + CertificateVerify]
2846
 * app data                       | Send Finished
2847
 * after   -->                    | K_send = application
2848
 * here                  +--------+--------+
2849
 *              No 0-RTT |                 | 0-RTT
2850
 *                       |                 |
2851
 *   K_recv = handshake  |                 | K_recv = early data
2852
 * [Skip decrypt errors] |    +------> WAIT_EOED -+
2853
 *                       |    |       Recv |      | Recv EndOfEarlyData
2854
 *                       |    | early data |      | K_recv = handshake
2855
 *                       |    +------------+      |
2856
 *                       |                        |
2857
 *                       +> WAIT_FLIGHT2 <--------+
2858
 *                                |
2859
 *                       +--------+--------+
2860
 *               No auth |                 | Client auth
2861
 *                       |                 |
2862
 *                       |                 v
2863
 *                       |             WAIT_CERT
2864
 *                       |        Recv |       | Recv Certificate
2865
 *                       |       empty |       v
2866
 *                       | Certificate |    WAIT_CV
2867
 *                       |             |       | Recv
2868
 *                       |             v       | CertificateVerify
2869
 *                       +-> WAIT_FINISHED <---+
2870
 *                                | Recv Finished
2871
 *
2872
 *
2873
 * The following function handles the state changes after WAIT_FLIGHT2 in the
2874
 * above diagram. We are not going to receive early data related messages
2875
 * anymore, prepare to receive the first handshake message of the client
2876
 * second flight.
2877
 */
2878
static void ssl_tls13_prepare_for_handshake_second_flight(
2879
    mbedtls_ssl_context *ssl)
2880
0
{
2881
0
    if (ssl->handshake->certificate_request_sent) {
2882
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE);
2883
0
    } else {
2884
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("skip parse certificate"));
2885
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("skip parse certificate verify"));
2886
2887
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_FINISHED);
2888
0
    }
2889
0
}
2890
2891
/*
2892
 * Handler for MBEDTLS_SSL_SERVER_FINISHED
2893
 */
2894
MBEDTLS_CHECK_RETURN_CRITICAL
2895
static int ssl_tls13_write_server_finished(mbedtls_ssl_context *ssl)
2896
0
{
2897
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2898
2899
0
    ret = mbedtls_ssl_tls13_write_finished_message(ssl);
2900
0
    if (ret != 0) {
2901
0
        return ret;
2902
0
    }
2903
2904
0
    ret = mbedtls_ssl_tls13_compute_application_transform(ssl);
2905
0
    if (ret != 0) {
2906
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(
2907
0
            MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE,
2908
0
            MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE);
2909
0
        return ret;
2910
0
    }
2911
2912
0
#if defined(MBEDTLS_SSL_EARLY_DATA)
2913
0
    if (ssl->handshake->early_data_accepted) {
2914
        /* See RFC 8446 section A.2 for more information */
2915
0
        MBEDTLS_SSL_DEBUG_MSG(
2916
0
            1, ("Switch to early keys for inbound traffic. "
2917
0
                "( K_recv = early data )"));
2918
0
        mbedtls_ssl_set_inbound_transform(
2919
0
            ssl, ssl->handshake->transform_earlydata);
2920
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_END_OF_EARLY_DATA);
2921
0
        return 0;
2922
0
    }
2923
0
#endif /* MBEDTLS_SSL_EARLY_DATA */
2924
0
    MBEDTLS_SSL_DEBUG_MSG(
2925
0
        1, ("Switch to handshake keys for inbound traffic "
2926
0
            "( K_recv = handshake )"));
2927
0
    mbedtls_ssl_set_inbound_transform(ssl, ssl->handshake->transform_handshake);
2928
2929
0
    ssl_tls13_prepare_for_handshake_second_flight(ssl);
2930
2931
0
    return 0;
2932
0
}
2933
2934
#if defined(MBEDTLS_SSL_EARLY_DATA)
2935
/*
2936
 * Handler for MBEDTLS_SSL_END_OF_EARLY_DATA
2937
 */
2938
0
#define SSL_GOT_END_OF_EARLY_DATA      0
2939
0
#define SSL_GOT_EARLY_DATA             1
2940
/* Coordination:
2941
 * Deals with the ambiguity of not knowing if the next message is an
2942
 * EndOfEarlyData message or an application message containing early data.
2943
 * Returns a negative code on failure, or
2944
 * - SSL_GOT_END_OF_EARLY_DATA
2945
 * - SSL_GOT_EARLY_DATA
2946
 * indicating which message is received.
2947
 */
2948
MBEDTLS_CHECK_RETURN_CRITICAL
2949
static int ssl_tls13_end_of_early_data_coordinate(mbedtls_ssl_context *ssl)
2950
0
{
2951
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2952
2953
0
    if ((ret = mbedtls_ssl_read_record(ssl, 0)) != 0) {
2954
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2955
0
        return ret;
2956
0
    }
2957
0
    ssl->keep_current_message = 1;
2958
2959
0
    if (ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE        &&
2960
0
        ssl->in_msg[0]  == MBEDTLS_SSL_HS_END_OF_EARLY_DATA) {
2961
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("Received an end_of_early_data message."));
2962
0
        return SSL_GOT_END_OF_EARLY_DATA;
2963
0
    }
2964
2965
0
    if (ssl->in_msgtype == MBEDTLS_SSL_MSG_APPLICATION_DATA) {
2966
0
        if (ssl->in_offt == NULL) {
2967
0
            MBEDTLS_SSL_DEBUG_MSG(3, ("Received early data"));
2968
            /* Set the reading pointer */
2969
0
            ssl->in_offt = ssl->in_msg;
2970
0
            ret = mbedtls_ssl_tls13_check_early_data_len(ssl, ssl->in_msglen);
2971
0
            if (ret != 0) {
2972
0
                return ret;
2973
0
            }
2974
0
        }
2975
0
        return SSL_GOT_EARLY_DATA;
2976
0
    }
2977
2978
0
    MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE,
2979
0
                                 MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE);
2980
0
    return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
2981
0
}
2982
2983
MBEDTLS_CHECK_RETURN_CRITICAL
2984
static int ssl_tls13_parse_end_of_early_data(mbedtls_ssl_context *ssl,
2985
                                             const unsigned char *buf,
2986
                                             const unsigned char *end)
2987
0
{
2988
    /* RFC 8446 section 4.5
2989
     *
2990
     * struct {} EndOfEarlyData;
2991
     */
2992
0
    if (buf != end) {
2993
0
        MBEDTLS_SSL_PEND_FATAL_ALERT(MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR,
2994
0
                                     MBEDTLS_ERR_SSL_DECODE_ERROR);
2995
0
        return MBEDTLS_ERR_SSL_DECODE_ERROR;
2996
0
    }
2997
0
    return 0;
2998
0
}
2999
3000
/*
3001
 * RFC 8446 section A.2
3002
 *
3003
 *                                | Send ServerHello
3004
 *                                | K_send = handshake
3005
 *                                | Send EncryptedExtensions
3006
 *                                | [Send CertificateRequest]
3007
 * Can send                       | [Send Certificate + CertificateVerify]
3008
 * app data                       | Send Finished
3009
 * after   -->                    | K_send = application
3010
 * here                  +--------+--------+
3011
 *              No 0-RTT |                 | 0-RTT
3012
 *                       |                 |
3013
 *   K_recv = handshake  |                 | K_recv = early data
3014
 * [Skip decrypt errors] |    +------> WAIT_EOED -+
3015
 *                       |    |       Recv |      | Recv EndOfEarlyData
3016
 *                       |    | early data |      | K_recv = handshake
3017
 *                       |    +------------+      |
3018
 *                       |                        |
3019
 *                       +> WAIT_FLIGHT2 <--------+
3020
 *                                |
3021
 *                       +--------+--------+
3022
 *               No auth |                 | Client auth
3023
 *                       |                 |
3024
 *                       |                 v
3025
 *                       |             WAIT_CERT
3026
 *                       |        Recv |       | Recv Certificate
3027
 *                       |       empty |       v
3028
 *                       | Certificate |    WAIT_CV
3029
 *                       |             |       | Recv
3030
 *                       |             v       | CertificateVerify
3031
 *                       +-> WAIT_FINISHED <---+
3032
 *                                | Recv Finished
3033
 *
3034
 * The function handles actions and state changes from 0-RTT to WAIT_FLIGHT2 in
3035
 * the above diagram.
3036
 */
3037
MBEDTLS_CHECK_RETURN_CRITICAL
3038
static int ssl_tls13_process_end_of_early_data(mbedtls_ssl_context *ssl)
3039
0
{
3040
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3041
3042
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> ssl_tls13_process_end_of_early_data"));
3043
3044
0
    MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_end_of_early_data_coordinate(ssl));
3045
3046
0
    if (ret == SSL_GOT_END_OF_EARLY_DATA) {
3047
0
        unsigned char *buf;
3048
0
        size_t buf_len;
3049
3050
0
        MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_tls13_fetch_handshake_msg(
3051
0
                                 ssl, MBEDTLS_SSL_HS_END_OF_EARLY_DATA,
3052
0
                                 &buf, &buf_len));
3053
3054
0
        MBEDTLS_SSL_PROC_CHK(ssl_tls13_parse_end_of_early_data(
3055
0
                                 ssl, buf, buf + buf_len));
3056
3057
0
        MBEDTLS_SSL_DEBUG_MSG(
3058
0
            1, ("Switch to handshake keys for inbound traffic"
3059
0
                "( K_recv = handshake )"));
3060
0
        mbedtls_ssl_set_inbound_transform(
3061
0
            ssl, ssl->handshake->transform_handshake);
3062
3063
0
        MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_add_hs_msg_to_checksum(
3064
0
                                 ssl, MBEDTLS_SSL_HS_END_OF_EARLY_DATA,
3065
0
                                 buf, buf_len));
3066
3067
0
        ssl_tls13_prepare_for_handshake_second_flight(ssl);
3068
3069
0
    } else if (ret == SSL_GOT_EARLY_DATA) {
3070
0
        ret = MBEDTLS_ERR_SSL_RECEIVED_EARLY_DATA;
3071
0
        goto cleanup;
3072
0
    } else {
3073
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
3074
0
        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3075
0
        goto cleanup;
3076
0
    }
3077
3078
0
cleanup:
3079
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= ssl_tls13_process_end_of_early_data"));
3080
0
    return ret;
3081
0
}
3082
#endif /* MBEDTLS_SSL_EARLY_DATA */
3083
3084
/*
3085
 * Handler for MBEDTLS_SSL_CLIENT_FINISHED
3086
 */
3087
MBEDTLS_CHECK_RETURN_CRITICAL
3088
static int ssl_tls13_process_client_finished(mbedtls_ssl_context *ssl)
3089
0
{
3090
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3091
3092
0
    ret = mbedtls_ssl_tls13_process_finished_message(ssl);
3093
0
    if (ret != 0) {
3094
0
        return ret;
3095
0
    }
3096
3097
0
    ret = mbedtls_ssl_tls13_compute_resumption_master_secret(ssl);
3098
0
    if (ret != 0) {
3099
0
        MBEDTLS_SSL_DEBUG_RET(
3100
0
            1, "mbedtls_ssl_tls13_compute_resumption_master_secret", ret);
3101
0
    }
3102
3103
0
    mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_WRAPUP);
3104
0
    return 0;
3105
0
}
3106
3107
/*
3108
 * Handler for MBEDTLS_SSL_HANDSHAKE_WRAPUP
3109
 */
3110
MBEDTLS_CHECK_RETURN_CRITICAL
3111
static int ssl_tls13_handshake_wrapup(mbedtls_ssl_context *ssl)
3112
0
{
3113
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("handshake: done"));
3114
3115
0
    mbedtls_ssl_tls13_handshake_wrapup(ssl);
3116
3117
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
3118
0
    defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
3119
/* TODO: Remove the check of SOME_PSK_ENABLED since SESSION_TICKETS requires
3120
 *       SOME_PSK_ENABLED to be enabled. Here is just to make CI happy. It is
3121
 *       expected to be resolved with issue#6395.
3122
 */
3123
    /* Sent NewSessionTicket message only when client supports PSK */
3124
0
    if (mbedtls_ssl_tls13_is_some_psk_supported(ssl)) {
3125
0
        mbedtls_ssl_handshake_set_state(
3126
0
            ssl, MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET);
3127
0
    } else
3128
0
#endif
3129
0
    {
3130
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
3131
0
    }
3132
0
    return 0;
3133
0
}
3134
3135
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
3136
/*
3137
 * Handler for MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET
3138
 */
3139
0
#define SSL_NEW_SESSION_TICKET_SKIP  0
3140
0
#define SSL_NEW_SESSION_TICKET_WRITE 1
3141
MBEDTLS_CHECK_RETURN_CRITICAL
3142
static int ssl_tls13_write_new_session_ticket_coordinate(mbedtls_ssl_context *ssl)
3143
0
{
3144
    /* Check whether the use of session tickets is enabled */
3145
0
    if (ssl->conf->f_ticket_write == NULL) {
3146
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("NewSessionTicket: disabled,"
3147
0
                                  " callback is not set"));
3148
0
        return SSL_NEW_SESSION_TICKET_SKIP;
3149
0
    }
3150
0
    if (ssl->conf->new_session_tickets_count == 0) {
3151
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("NewSessionTicket: disabled,"
3152
0
                                  " configured count is zero"));
3153
0
        return SSL_NEW_SESSION_TICKET_SKIP;
3154
0
    }
3155
3156
0
    if (ssl->handshake->new_session_tickets_count == 0) {
3157
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("NewSessionTicket: all tickets have "
3158
0
                                  "been sent."));
3159
0
        return SSL_NEW_SESSION_TICKET_SKIP;
3160
0
    }
3161
3162
0
    return SSL_NEW_SESSION_TICKET_WRITE;
3163
0
}
3164
3165
MBEDTLS_CHECK_RETURN_CRITICAL
3166
static int ssl_tls13_prepare_new_session_ticket(mbedtls_ssl_context *ssl,
3167
                                                unsigned char *ticket_nonce,
3168
                                                size_t ticket_nonce_size)
3169
0
{
3170
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3171
0
    mbedtls_ssl_session *session = ssl->session;
3172
0
    mbedtls_ssl_ciphersuite_t *ciphersuite_info;
3173
0
    psa_algorithm_t psa_hash_alg;
3174
0
    int hash_length;
3175
3176
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> prepare NewSessionTicket msg"));
3177
3178
    /* Set ticket_flags depends on the advertised psk key exchange mode */
3179
0
    mbedtls_ssl_tls13_session_clear_ticket_flags(
3180
0
        session, MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK);
3181
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
3182
0
    mbedtls_ssl_tls13_session_set_ticket_flags(
3183
0
        session, ssl->handshake->tls13_kex_modes);
3184
0
#endif
3185
3186
0
#if defined(MBEDTLS_SSL_EARLY_DATA)
3187
0
    if (ssl->conf->early_data_enabled == MBEDTLS_SSL_EARLY_DATA_ENABLED &&
3188
0
        ssl->conf->max_early_data_size > 0) {
3189
0
        mbedtls_ssl_tls13_session_set_ticket_flags(
3190
0
            session, MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA);
3191
0
        session->max_early_data_size = ssl->conf->max_early_data_size;
3192
0
    }
3193
0
#endif /* MBEDTLS_SSL_EARLY_DATA */
3194
3195
0
    MBEDTLS_SSL_PRINT_TICKET_FLAGS(4, session->ticket_flags);
3196
3197
0
#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_ALPN)
3198
0
    if (session->ticket_alpn == NULL) {
3199
0
        ret = mbedtls_ssl_session_set_ticket_alpn(session, ssl->alpn_chosen);
3200
0
        if (ret != 0) {
3201
0
            return ret;
3202
0
        }
3203
0
    }
3204
0
#endif
3205
3206
    /* Generate ticket_age_add */
3207
0
    if ((ret = ssl->conf->f_rng(ssl->conf->p_rng,
3208
0
                                (unsigned char *) &session->ticket_age_add,
3209
0
                                sizeof(session->ticket_age_add)) != 0)) {
3210
0
        MBEDTLS_SSL_DEBUG_RET(1, "generate_ticket_age_add", ret);
3211
0
        return ret;
3212
0
    }
3213
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_age_add: %u",
3214
0
                              (unsigned int) session->ticket_age_add));
3215
3216
    /* Generate ticket_nonce */
3217
0
    ret = ssl->conf->f_rng(ssl->conf->p_rng, ticket_nonce, ticket_nonce_size);
3218
0
    if (ret != 0) {
3219
0
        MBEDTLS_SSL_DEBUG_RET(1, "generate_ticket_nonce", ret);
3220
0
        return ret;
3221
0
    }
3222
0
    MBEDTLS_SSL_DEBUG_BUF(3, "ticket_nonce:",
3223
0
                          ticket_nonce, ticket_nonce_size);
3224
3225
0
    ciphersuite_info =
3226
0
        (mbedtls_ssl_ciphersuite_t *) ssl->handshake->ciphersuite_info;
3227
0
    psa_hash_alg = mbedtls_md_psa_alg_from_type((mbedtls_md_type_t) ciphersuite_info->mac);
3228
0
    hash_length = PSA_HASH_LENGTH(psa_hash_alg);
3229
0
    if (hash_length == -1 ||
3230
0
        (size_t) hash_length > sizeof(session->resumption_key)) {
3231
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
3232
0
    }
3233
3234
    /* In this code the psk key length equals the length of the hash */
3235
0
    session->resumption_key_len = hash_length;
3236
0
    session->ciphersuite = ciphersuite_info->id;
3237
3238
    /* Compute resumption key
3239
     *
3240
     *  HKDF-Expand-Label( resumption_master_secret,
3241
     *                    "resumption", ticket_nonce, Hash.length )
3242
     */
3243
0
    ret = mbedtls_ssl_tls13_hkdf_expand_label(
3244
0
        psa_hash_alg,
3245
0
        session->app_secrets.resumption_master_secret,
3246
0
        hash_length,
3247
0
        MBEDTLS_SSL_TLS1_3_LBL_WITH_LEN(resumption),
3248
0
        ticket_nonce,
3249
0
        ticket_nonce_size,
3250
0
        session->resumption_key,
3251
0
        hash_length);
3252
3253
0
    if (ret != 0) {
3254
0
        MBEDTLS_SSL_DEBUG_RET(2,
3255
0
                              "Creating the ticket-resumed PSK failed",
3256
0
                              ret);
3257
0
        return ret;
3258
0
    }
3259
0
    MBEDTLS_SSL_DEBUG_BUF(3, "Ticket-resumed PSK",
3260
0
                          session->resumption_key,
3261
0
                          session->resumption_key_len);
3262
3263
0
    MBEDTLS_SSL_DEBUG_BUF(3, "resumption_master_secret",
3264
0
                          session->app_secrets.resumption_master_secret,
3265
0
                          hash_length);
3266
3267
0
    return 0;
3268
0
}
3269
3270
/* This function creates a NewSessionTicket message in the following format:
3271
 *
3272
 * struct {
3273
 *    uint32 ticket_lifetime;
3274
 *    uint32 ticket_age_add;
3275
 *    opaque ticket_nonce<0..255>;
3276
 *    opaque ticket<1..2^16-1>;
3277
 *    Extension extensions<0..2^16-2>;
3278
 * } NewSessionTicket;
3279
 *
3280
 * The ticket inside the NewSessionTicket message is an encrypted container
3281
 * carrying the necessary information so that the server is later able to
3282
 * re-start the communication.
3283
 *
3284
 * The following fields are placed inside the ticket by the
3285
 * f_ticket_write() function:
3286
 *
3287
 *  - creation time (ticket_creation_time)
3288
 *  - flags (ticket_flags)
3289
 *  - age add (ticket_age_add)
3290
 *  - key (resumption_key)
3291
 *  - key length (resumption_key_len)
3292
 *  - ciphersuite (ciphersuite)
3293
 *  - max_early_data_size (max_early_data_size)
3294
 */
3295
MBEDTLS_CHECK_RETURN_CRITICAL
3296
static int ssl_tls13_write_new_session_ticket_body(mbedtls_ssl_context *ssl,
3297
                                                   unsigned char *buf,
3298
                                                   unsigned char *end,
3299
                                                   size_t *out_len,
3300
                                                   unsigned char *ticket_nonce,
3301
                                                   size_t ticket_nonce_size)
3302
0
{
3303
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3304
0
    unsigned char *p = buf;
3305
0
    mbedtls_ssl_session *session = ssl->session;
3306
0
    size_t ticket_len;
3307
0
    uint32_t ticket_lifetime;
3308
0
    unsigned char *p_extensions_len;
3309
3310
0
    *out_len = 0;
3311
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write NewSessionTicket msg"));
3312
3313
    /*
3314
     *    ticket_lifetime   4 bytes
3315
     *    ticket_age_add    4 bytes
3316
     *    ticket_nonce      1 + ticket_nonce_size bytes
3317
     *    ticket            >=2 bytes
3318
     */
3319
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 4 + 4 + 1 + ticket_nonce_size + 2);
3320
3321
    /* Generate ticket and ticket_lifetime */
3322
0
#if defined(MBEDTLS_HAVE_TIME)
3323
0
    session->ticket_creation_time = mbedtls_ms_time();
3324
0
#endif
3325
0
    ret = ssl->conf->f_ticket_write(ssl->conf->p_ticket,
3326
0
                                    session,
3327
0
                                    p + 9 + ticket_nonce_size + 2,
3328
0
                                    end,
3329
0
                                    &ticket_len,
3330
0
                                    &ticket_lifetime);
3331
0
    if (ret != 0) {
3332
0
        MBEDTLS_SSL_DEBUG_RET(1, "write_ticket", ret);
3333
0
        return ret;
3334
0
    }
3335
3336
    /* RFC 8446 section 4.6.1
3337
     *
3338
     *  ticket_lifetime:  Indicates the lifetime in seconds as a 32-bit
3339
     *     unsigned integer in network byte order from the time of ticket
3340
     *     issuance.  Servers MUST NOT use any value greater than
3341
     *     604800 seconds (7 days) ...
3342
     */
3343
0
    if (ticket_lifetime > MBEDTLS_SSL_TLS1_3_MAX_ALLOWED_TICKET_LIFETIME) {
3344
0
        MBEDTLS_SSL_DEBUG_MSG(
3345
0
            1, ("Ticket lifetime (%u) is greater than 7 days.",
3346
0
                (unsigned int) ticket_lifetime));
3347
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3348
0
    }
3349
3350
0
    MBEDTLS_PUT_UINT32_BE(ticket_lifetime, p, 0);
3351
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_lifetime: %u",
3352
0
                              (unsigned int) ticket_lifetime));
3353
3354
    /* Write ticket_age_add */
3355
0
    MBEDTLS_PUT_UINT32_BE(session->ticket_age_add, p, 4);
3356
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("ticket_age_add: %u",
3357
0
                              (unsigned int) session->ticket_age_add));
3358
3359
    /* Write ticket_nonce */
3360
0
    p[8] = (unsigned char) ticket_nonce_size;
3361
0
    if (ticket_nonce_size > 0) {
3362
0
        memcpy(p + 9, ticket_nonce, ticket_nonce_size);
3363
0
    }
3364
0
    p += 9 + ticket_nonce_size;
3365
3366
    /* Write ticket */
3367
0
    MBEDTLS_PUT_UINT16_BE(ticket_len, p, 0);
3368
0
    p += 2;
3369
0
    MBEDTLS_SSL_DEBUG_BUF(4, "ticket", p, ticket_len);
3370
0
    p += ticket_len;
3371
3372
    /* Ticket Extensions
3373
     *
3374
     * Extension extensions<0..2^16-2>;
3375
     */
3376
0
    ssl->handshake->sent_extensions = MBEDTLS_SSL_EXT_MASK_NONE;
3377
3378
0
    MBEDTLS_SSL_CHK_BUF_PTR(p, end, 2);
3379
0
    p_extensions_len = p;
3380
0
    p += 2;
3381
3382
0
#if defined(MBEDTLS_SSL_EARLY_DATA)
3383
0
    if (mbedtls_ssl_tls13_session_ticket_allow_early_data(session)) {
3384
0
        size_t output_len;
3385
3386
0
        if ((ret = mbedtls_ssl_tls13_write_early_data_ext(
3387
0
                 ssl, 1, p, end, &output_len)) != 0) {
3388
0
            MBEDTLS_SSL_DEBUG_RET(
3389
0
                1, "mbedtls_ssl_tls13_write_early_data_ext", ret);
3390
0
            return ret;
3391
0
        }
3392
0
        p += output_len;
3393
0
    } else {
3394
0
        MBEDTLS_SSL_DEBUG_MSG(
3395
0
            4, ("early_data not allowed, "
3396
0
                "skip early_data extension in NewSessionTicket"));
3397
0
    }
3398
3399
0
#endif /* MBEDTLS_SSL_EARLY_DATA */
3400
3401
0
    MBEDTLS_PUT_UINT16_BE(p - p_extensions_len - 2, p_extensions_len, 0);
3402
3403
0
    *out_len = p - buf;
3404
0
    MBEDTLS_SSL_DEBUG_BUF(4, "ticket", buf, *out_len);
3405
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write new session ticket"));
3406
3407
0
    MBEDTLS_SSL_PRINT_EXTS(
3408
0
        3, MBEDTLS_SSL_HS_NEW_SESSION_TICKET, ssl->handshake->sent_extensions);
3409
3410
0
    return 0;
3411
0
}
3412
3413
/*
3414
 * Handler for MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET
3415
 */
3416
static int ssl_tls13_write_new_session_ticket(mbedtls_ssl_context *ssl)
3417
0
{
3418
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3419
3420
0
    MBEDTLS_SSL_PROC_CHK_NEG(ssl_tls13_write_new_session_ticket_coordinate(ssl));
3421
3422
0
    if (ret == SSL_NEW_SESSION_TICKET_WRITE) {
3423
0
        unsigned char ticket_nonce[MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH];
3424
0
        unsigned char *buf;
3425
0
        size_t buf_len, msg_len;
3426
3427
0
        MBEDTLS_SSL_PROC_CHK(ssl_tls13_prepare_new_session_ticket(
3428
0
                                 ssl, ticket_nonce, sizeof(ticket_nonce)));
3429
3430
0
        MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_start_handshake_msg(
3431
0
                                 ssl, MBEDTLS_SSL_HS_NEW_SESSION_TICKET,
3432
0
                                 &buf, &buf_len));
3433
3434
0
        MBEDTLS_SSL_PROC_CHK(ssl_tls13_write_new_session_ticket_body(
3435
0
                                 ssl, buf, buf + buf_len, &msg_len,
3436
0
                                 ticket_nonce, sizeof(ticket_nonce)));
3437
3438
0
        MBEDTLS_SSL_PROC_CHK(mbedtls_ssl_finish_handshake_msg(
3439
0
                                 ssl, buf_len, msg_len));
3440
3441
        /* Limit session tickets count to one when resumption connection.
3442
         *
3443
         * See document of mbedtls_ssl_conf_new_session_tickets.
3444
         */
3445
0
        if (ssl->handshake->resume == 1) {
3446
0
            ssl->handshake->new_session_tickets_count = 0;
3447
0
        } else {
3448
0
            ssl->handshake->new_session_tickets_count--;
3449
0
        }
3450
3451
0
        mbedtls_ssl_handshake_set_state(
3452
0
            ssl, MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET_FLUSH);
3453
0
    } else {
3454
0
        mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
3455
0
    }
3456
3457
0
cleanup:
3458
3459
0
    return ret;
3460
0
}
3461
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
3462
3463
/*
3464
 * TLS 1.3 State Machine -- server side
3465
 */
3466
int mbedtls_ssl_tls13_handshake_server_step(mbedtls_ssl_context *ssl)
3467
3.68k
{
3468
3.68k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3469
3470
3.68k
    if (ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL) {
3471
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
3472
0
    }
3473
3474
3.68k
    MBEDTLS_SSL_DEBUG_MSG(2, ("tls13 server state: %s(%d)",
3475
3.68k
                              mbedtls_ssl_states_str((mbedtls_ssl_states) ssl->state),
3476
3.68k
                              ssl->state));
3477
3478
3.68k
    switch (ssl->state) {
3479
        /* start state */
3480
1.84k
        case MBEDTLS_SSL_HELLO_REQUEST:
3481
1.84k
            mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
3482
1.84k
            ret = 0;
3483
1.84k
            break;
3484
3485
1.84k
        case MBEDTLS_SSL_CLIENT_HELLO:
3486
1.84k
            ret = ssl_tls13_process_client_hello(ssl);
3487
1.84k
            if (ret != 0) {
3488
560
                MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_process_client_hello", ret);
3489
560
            }
3490
1.84k
            break;
3491
3492
0
        case MBEDTLS_SSL_HELLO_RETRY_REQUEST:
3493
0
            ret = ssl_tls13_write_hello_retry_request(ssl);
3494
0
            if (ret != 0) {
3495
0
                MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_write_hello_retry_request", ret);
3496
0
                return ret;
3497
0
            }
3498
0
            break;
3499
3500
0
        case MBEDTLS_SSL_SERVER_HELLO:
3501
0
            ret = ssl_tls13_write_server_hello(ssl);
3502
0
            break;
3503
3504
0
        case MBEDTLS_SSL_ENCRYPTED_EXTENSIONS:
3505
0
            ret = ssl_tls13_write_encrypted_extensions(ssl);
3506
0
            if (ret != 0) {
3507
0
                MBEDTLS_SSL_DEBUG_RET(1, "ssl_tls13_write_encrypted_extensions", ret);
3508
0
                return ret;
3509
0
            }
3510
0
            break;
3511
3512
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
3513
0
        case MBEDTLS_SSL_CERTIFICATE_REQUEST:
3514
0
            ret = ssl_tls13_write_certificate_request(ssl);
3515
0
            break;
3516
3517
0
        case MBEDTLS_SSL_SERVER_CERTIFICATE:
3518
0
            ret = ssl_tls13_write_server_certificate(ssl);
3519
0
            break;
3520
3521
0
        case MBEDTLS_SSL_CERTIFICATE_VERIFY:
3522
0
            ret = ssl_tls13_write_certificate_verify(ssl);
3523
0
            break;
3524
0
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
3525
3526
            /*
3527
             * Injection of dummy-CCS's for middlebox compatibility
3528
             */
3529
0
#if defined(MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE)
3530
0
        case MBEDTLS_SSL_SERVER_CCS_AFTER_HELLO_RETRY_REQUEST:
3531
0
            ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
3532
0
            if (ret == 0) {
3533
0
                mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_CLIENT_HELLO);
3534
0
            }
3535
0
            break;
3536
3537
0
        case MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO:
3538
0
            ret = mbedtls_ssl_tls13_write_change_cipher_spec(ssl);
3539
0
            if (ret != 0) {
3540
0
                break;
3541
0
            }
3542
0
            mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_ENCRYPTED_EXTENSIONS);
3543
0
            break;
3544
0
#endif /* MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE */
3545
3546
0
        case MBEDTLS_SSL_SERVER_FINISHED:
3547
0
            ret = ssl_tls13_write_server_finished(ssl);
3548
0
            break;
3549
3550
0
#if defined(MBEDTLS_SSL_EARLY_DATA)
3551
0
        case MBEDTLS_SSL_END_OF_EARLY_DATA:
3552
0
            ret = ssl_tls13_process_end_of_early_data(ssl);
3553
0
            break;
3554
0
#endif /* MBEDTLS_SSL_EARLY_DATA */
3555
3556
0
        case MBEDTLS_SSL_CLIENT_FINISHED:
3557
0
            ret = ssl_tls13_process_client_finished(ssl);
3558
0
            break;
3559
3560
0
        case MBEDTLS_SSL_HANDSHAKE_WRAPUP:
3561
0
            ret = ssl_tls13_handshake_wrapup(ssl);
3562
0
            break;
3563
3564
0
#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
3565
0
        case MBEDTLS_SSL_CLIENT_CERTIFICATE:
3566
0
            ret = mbedtls_ssl_tls13_process_certificate(ssl);
3567
0
            if (ret == 0) {
3568
0
                if (ssl->session_negotiate->peer_cert != NULL) {
3569
0
                    mbedtls_ssl_handshake_set_state(
3570
0
                        ssl, MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY);
3571
0
                } else {
3572
0
                    MBEDTLS_SSL_DEBUG_MSG(2, ("skip parse certificate verify"));
3573
0
                    mbedtls_ssl_handshake_set_state(
3574
0
                        ssl, MBEDTLS_SSL_CLIENT_FINISHED);
3575
0
                }
3576
0
            }
3577
0
            break;
3578
3579
0
        case MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY:
3580
0
            ret = mbedtls_ssl_tls13_process_certificate_verify(ssl);
3581
0
            if (ret == 0) {
3582
0
                mbedtls_ssl_handshake_set_state(
3583
0
                    ssl, MBEDTLS_SSL_CLIENT_FINISHED);
3584
0
            }
3585
0
            break;
3586
0
#endif /* MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED */
3587
3588
0
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
3589
0
        case MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET:
3590
0
            ret = ssl_tls13_write_new_session_ticket(ssl);
3591
0
            if (ret != 0) {
3592
0
                MBEDTLS_SSL_DEBUG_RET(1,
3593
0
                                      "ssl_tls13_write_new_session_ticket ",
3594
0
                                      ret);
3595
0
            }
3596
0
            break;
3597
0
        case MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET_FLUSH:
3598
            /* This state is necessary to do the flush of the New Session
3599
             * Ticket message written in MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET
3600
             * as part of ssl_prepare_handshake_step.
3601
             */
3602
0
            ret = 0;
3603
3604
0
            if (ssl->handshake->new_session_tickets_count == 0) {
3605
0
                mbedtls_ssl_handshake_set_state(ssl, MBEDTLS_SSL_HANDSHAKE_OVER);
3606
0
            } else {
3607
0
                mbedtls_ssl_handshake_set_state(
3608
0
                    ssl, MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET);
3609
0
            }
3610
0
            break;
3611
3612
0
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
3613
3614
0
        default:
3615
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("invalid state %d", ssl->state));
3616
0
            return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3617
3.68k
    }
3618
3619
3.68k
    return ret;
3620
3.68k
}
3621
3622
#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_PROTO_TLS1_3 */