Coverage Report

Created: 2024-05-20 06:02

/src/openthread/third_party/mbedtls/repo/library/ssl_tls.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 *  SSLv3/TLSv1 shared functions
3
 *
4
 *  Copyright The Mbed TLS Contributors
5
 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6
 */
7
/*
8
 *  The SSL 3.0 specification was drafted by Netscape in 1996,
9
 *  and became an IETF standard in 1999.
10
 *
11
 *  http://wp.netscape.com/eng/ssl3/
12
 *  http://www.ietf.org/rfc/rfc2246.txt
13
 *  http://www.ietf.org/rfc/rfc4346.txt
14
 */
15
16
#include "common.h"
17
18
#if defined(MBEDTLS_SSL_TLS_C)
19
20
#include "mbedtls/platform.h"
21
22
#include "mbedtls/ssl.h"
23
#include "mbedtls/ssl_internal.h"
24
#include "mbedtls/debug.h"
25
#include "mbedtls/error.h"
26
#include "mbedtls/platform_util.h"
27
#include "mbedtls/version.h"
28
#include "mbedtls/constant_time.h"
29
30
#include <string.h>
31
32
#if defined(MBEDTLS_USE_PSA_CRYPTO)
33
#include "mbedtls/psa_util.h"
34
#include "psa/crypto.h"
35
#endif
36
37
#if defined(MBEDTLS_X509_CRT_PARSE_C)
38
#include "mbedtls/oid.h"
39
#endif
40
41
#if defined(MBEDTLS_SSL_PROTO_DTLS)
42
43
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
44
/* Top-level Connection ID API */
45
46
int mbedtls_ssl_conf_cid(mbedtls_ssl_config *conf,
47
                         size_t len,
48
                         int ignore_other_cid)
49
{
50
    if (len > MBEDTLS_SSL_CID_IN_LEN_MAX) {
51
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
52
    }
53
54
    if (ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_FAIL &&
55
        ignore_other_cid != MBEDTLS_SSL_UNEXPECTED_CID_IGNORE) {
56
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
57
    }
58
59
    conf->ignore_unexpected_cid = ignore_other_cid;
60
    conf->cid_len = len;
61
    return 0;
62
}
63
64
int mbedtls_ssl_set_cid(mbedtls_ssl_context *ssl,
65
                        int enable,
66
                        unsigned char const *own_cid,
67
                        size_t own_cid_len)
68
{
69
    if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
70
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
71
    }
72
73
    ssl->negotiate_cid = enable;
74
    if (enable == MBEDTLS_SSL_CID_DISABLED) {
75
        MBEDTLS_SSL_DEBUG_MSG(3, ("Disable use of CID extension."));
76
        return 0;
77
    }
78
    MBEDTLS_SSL_DEBUG_MSG(3, ("Enable use of CID extension."));
79
    MBEDTLS_SSL_DEBUG_BUF(3, "Own CID", own_cid, own_cid_len);
80
81
    if (own_cid_len != ssl->conf->cid_len) {
82
        MBEDTLS_SSL_DEBUG_MSG(3, ("CID length %u does not match CID length %u in config",
83
                                  (unsigned) own_cid_len,
84
                                  (unsigned) ssl->conf->cid_len));
85
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
86
    }
87
88
    memcpy(ssl->own_cid, own_cid, own_cid_len);
89
    /* Truncation is not an issue here because
90
     * MBEDTLS_SSL_CID_IN_LEN_MAX at most 255. */
91
    ssl->own_cid_len = (uint8_t) own_cid_len;
92
93
    return 0;
94
}
95
96
int mbedtls_ssl_get_peer_cid(mbedtls_ssl_context *ssl,
97
                             int *enabled,
98
                             unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],
99
                             size_t *peer_cid_len)
100
{
101
    *enabled = MBEDTLS_SSL_CID_DISABLED;
102
103
    if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
104
        ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
105
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
106
    }
107
108
    /* We report MBEDTLS_SSL_CID_DISABLED in case the CID extensions
109
     * were used, but client and server requested the empty CID.
110
     * This is indistinguishable from not using the CID extension
111
     * in the first place. */
112
    if (ssl->transform_in->in_cid_len  == 0 &&
113
        ssl->transform_in->out_cid_len == 0) {
114
        return 0;
115
    }
116
117
    if (peer_cid_len != NULL) {
118
        *peer_cid_len = ssl->transform_in->out_cid_len;
119
        if (peer_cid != NULL) {
120
            memcpy(peer_cid, ssl->transform_in->out_cid,
121
                   ssl->transform_in->out_cid_len);
122
        }
123
    }
124
125
    *enabled = MBEDTLS_SSL_CID_ENABLED;
126
127
    return 0;
128
}
129
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
130
131
#endif /* MBEDTLS_SSL_PROTO_DTLS */
132
133
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
134
/*
135
 * Convert max_fragment_length codes to length.
136
 * RFC 6066 says:
137
 *    enum{
138
 *        2^9(1), 2^10(2), 2^11(3), 2^12(4), (255)
139
 *    } MaxFragmentLength;
140
 * and we add 0 -> extension unused
141
 */
142
static unsigned int ssl_mfl_code_to_length(int mfl)
143
0
{
144
0
    switch (mfl) {
145
0
        case MBEDTLS_SSL_MAX_FRAG_LEN_NONE:
146
0
            return MBEDTLS_TLS_EXT_ADV_CONTENT_LEN;
147
0
        case MBEDTLS_SSL_MAX_FRAG_LEN_512:
148
0
            return 512;
149
0
        case MBEDTLS_SSL_MAX_FRAG_LEN_1024:
150
0
            return 1024;
151
0
        case MBEDTLS_SSL_MAX_FRAG_LEN_2048:
152
0
            return 2048;
153
0
        case MBEDTLS_SSL_MAX_FRAG_LEN_4096:
154
0
            return 4096;
155
0
        default:
156
0
            return MBEDTLS_TLS_EXT_ADV_CONTENT_LEN;
157
0
    }
158
0
}
159
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
160
161
int mbedtls_ssl_session_copy(mbedtls_ssl_session *dst,
162
                             const mbedtls_ssl_session *src)
163
0
{
164
0
    mbedtls_ssl_session_free(dst);
165
0
    memcpy(dst, src, sizeof(mbedtls_ssl_session));
166
167
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
168
    dst->ticket = NULL;
169
#endif
170
171
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
172
173
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
174
    if (src->peer_cert != NULL) {
175
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
176
177
        dst->peer_cert = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
178
        if (dst->peer_cert == NULL) {
179
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
180
        }
181
182
        mbedtls_x509_crt_init(dst->peer_cert);
183
184
        if ((ret = mbedtls_x509_crt_parse_der(dst->peer_cert, src->peer_cert->raw.p,
185
                                              src->peer_cert->raw.len)) != 0) {
186
            mbedtls_free(dst->peer_cert);
187
            dst->peer_cert = NULL;
188
            return ret;
189
        }
190
    }
191
#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
192
0
    if (src->peer_cert_digest != NULL) {
193
0
        dst->peer_cert_digest =
194
0
            mbedtls_calloc(1, src->peer_cert_digest_len);
195
0
        if (dst->peer_cert_digest == NULL) {
196
0
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
197
0
        }
198
199
0
        memcpy(dst->peer_cert_digest, src->peer_cert_digest,
200
0
               src->peer_cert_digest_len);
201
0
        dst->peer_cert_digest_type = src->peer_cert_digest_type;
202
0
        dst->peer_cert_digest_len = src->peer_cert_digest_len;
203
0
    }
204
0
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
205
206
0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
207
208
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
209
    if (src->ticket != NULL) {
210
        dst->ticket = mbedtls_calloc(1, src->ticket_len);
211
        if (dst->ticket == NULL) {
212
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
213
        }
214
215
        memcpy(dst->ticket, src->ticket, src->ticket_len);
216
    }
217
#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
218
219
0
    return 0;
220
0
}
221
222
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
223
MBEDTLS_CHECK_RETURN_CRITICAL
224
static int resize_buffer(unsigned char **buffer, size_t len_new, size_t *len_old)
225
{
226
    unsigned char *resized_buffer = mbedtls_calloc(1, len_new);
227
    if (resized_buffer == NULL) {
228
        return -1;
229
    }
230
231
    /* We want to copy len_new bytes when downsizing the buffer, and
232
     * len_old bytes when upsizing, so we choose the smaller of two sizes,
233
     * to fit one buffer into another. Size checks, ensuring that no data is
234
     * lost, are done outside of this function. */
235
    memcpy(resized_buffer, *buffer,
236
           (len_new < *len_old) ? len_new : *len_old);
237
    mbedtls_platform_zeroize(*buffer, *len_old);
238
    mbedtls_free(*buffer);
239
240
    *buffer = resized_buffer;
241
    *len_old = len_new;
242
243
    return 0;
244
}
245
246
static void handle_buffer_resizing(mbedtls_ssl_context *ssl, int downsizing,
247
                                   size_t in_buf_new_len,
248
                                   size_t out_buf_new_len)
249
{
250
    int modified = 0;
251
    size_t written_in = 0, iv_offset_in = 0, len_offset_in = 0;
252
    size_t written_out = 0, iv_offset_out = 0, len_offset_out = 0;
253
    if (ssl->in_buf != NULL) {
254
        written_in = ssl->in_msg - ssl->in_buf;
255
        iv_offset_in = ssl->in_iv - ssl->in_buf;
256
        len_offset_in = ssl->in_len - ssl->in_buf;
257
        if (downsizing ?
258
            ssl->in_buf_len > in_buf_new_len && ssl->in_left < in_buf_new_len :
259
            ssl->in_buf_len < in_buf_new_len) {
260
            if (resize_buffer(&ssl->in_buf, in_buf_new_len, &ssl->in_buf_len) != 0) {
261
                MBEDTLS_SSL_DEBUG_MSG(1, ("input buffer resizing failed - out of memory"));
262
            } else {
263
                MBEDTLS_SSL_DEBUG_MSG(2, ("Reallocating in_buf to %" MBEDTLS_PRINTF_SIZET,
264
                                          in_buf_new_len));
265
                modified = 1;
266
            }
267
        }
268
    }
269
270
    if (ssl->out_buf != NULL) {
271
        written_out = ssl->out_msg - ssl->out_buf;
272
        iv_offset_out = ssl->out_iv - ssl->out_buf;
273
        len_offset_out = ssl->out_len - ssl->out_buf;
274
        if (downsizing ?
275
            ssl->out_buf_len > out_buf_new_len && ssl->out_left < out_buf_new_len :
276
            ssl->out_buf_len < out_buf_new_len) {
277
            if (resize_buffer(&ssl->out_buf, out_buf_new_len, &ssl->out_buf_len) != 0) {
278
                MBEDTLS_SSL_DEBUG_MSG(1, ("output buffer resizing failed - out of memory"));
279
            } else {
280
                MBEDTLS_SSL_DEBUG_MSG(2, ("Reallocating out_buf to %" MBEDTLS_PRINTF_SIZET,
281
                                          out_buf_new_len));
282
                modified = 1;
283
            }
284
        }
285
    }
286
    if (modified) {
287
        /* Update pointers here to avoid doing it twice. */
288
        mbedtls_ssl_reset_in_out_pointers(ssl);
289
        /* Fields below might not be properly updated with record
290
         * splitting or with CID, so they are manually updated here. */
291
        ssl->out_msg = ssl->out_buf + written_out;
292
        ssl->out_len = ssl->out_buf + len_offset_out;
293
        ssl->out_iv = ssl->out_buf + iv_offset_out;
294
295
        ssl->in_msg = ssl->in_buf + written_in;
296
        ssl->in_len = ssl->in_buf + len_offset_in;
297
        ssl->in_iv = ssl->in_buf + iv_offset_in;
298
    }
299
}
300
#endif /* MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH */
301
302
/*
303
 * Key material generation
304
 */
305
#if defined(MBEDTLS_SSL_PROTO_SSL3)
306
MBEDTLS_CHECK_RETURN_CRITICAL
307
static int ssl3_prf(const unsigned char *secret, size_t slen,
308
                    const char *label,
309
                    const unsigned char *random, size_t rlen,
310
                    unsigned char *dstbuf, size_t dlen)
311
{
312
    int ret = 0;
313
    size_t i;
314
    mbedtls_md5_context md5;
315
    mbedtls_sha1_context sha1;
316
    unsigned char padding[16];
317
    unsigned char sha1sum[20];
318
    ((void) label);
319
320
    mbedtls_md5_init(&md5);
321
    mbedtls_sha1_init(&sha1);
322
323
    /*
324
     *  SSLv3:
325
     *    block =
326
     *      MD5( secret + SHA1( 'A'    + secret + random ) ) +
327
     *      MD5( secret + SHA1( 'BB'   + secret + random ) ) +
328
     *      MD5( secret + SHA1( 'CCC'  + secret + random ) ) +
329
     *      ...
330
     */
331
    for (i = 0; i < dlen / 16; i++) {
332
        memset(padding, (unsigned char) ('A' + i), 1 + i);
333
334
        if ((ret = mbedtls_sha1_starts_ret(&sha1)) != 0) {
335
            goto exit;
336
        }
337
        if ((ret = mbedtls_sha1_update_ret(&sha1, padding, 1 + i)) != 0) {
338
            goto exit;
339
        }
340
        if ((ret = mbedtls_sha1_update_ret(&sha1, secret, slen)) != 0) {
341
            goto exit;
342
        }
343
        if ((ret = mbedtls_sha1_update_ret(&sha1, random, rlen)) != 0) {
344
            goto exit;
345
        }
346
        if ((ret = mbedtls_sha1_finish_ret(&sha1, sha1sum)) != 0) {
347
            goto exit;
348
        }
349
350
        if ((ret = mbedtls_md5_starts_ret(&md5)) != 0) {
351
            goto exit;
352
        }
353
        if ((ret = mbedtls_md5_update_ret(&md5, secret, slen)) != 0) {
354
            goto exit;
355
        }
356
        if ((ret = mbedtls_md5_update_ret(&md5, sha1sum, 20)) != 0) {
357
            goto exit;
358
        }
359
        if ((ret = mbedtls_md5_finish_ret(&md5, dstbuf + i * 16)) != 0) {
360
            goto exit;
361
        }
362
    }
363
364
exit:
365
    mbedtls_md5_free(&md5);
366
    mbedtls_sha1_free(&sha1);
367
368
    mbedtls_platform_zeroize(padding, sizeof(padding));
369
    mbedtls_platform_zeroize(sha1sum, sizeof(sha1sum));
370
371
    return ret;
372
}
373
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
374
375
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
376
MBEDTLS_CHECK_RETURN_CRITICAL
377
static int tls1_prf(const unsigned char *secret, size_t slen,
378
                    const char *label,
379
                    const unsigned char *random, size_t rlen,
380
                    unsigned char *dstbuf, size_t dlen)
381
{
382
    size_t nb, hs;
383
    size_t i, j, k;
384
    const unsigned char *S1, *S2;
385
    unsigned char *tmp;
386
    size_t tmp_len = 0;
387
    unsigned char h_i[20];
388
    const mbedtls_md_info_t *md_info;
389
    mbedtls_md_context_t md_ctx;
390
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
391
392
    mbedtls_md_init(&md_ctx);
393
394
    tmp_len = 20 + strlen(label) + rlen;
395
    tmp = mbedtls_calloc(1, tmp_len);
396
    if (tmp == NULL) {
397
        ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
398
        goto exit;
399
    }
400
401
    hs = (slen + 1) / 2;
402
    S1 = secret;
403
    S2 = secret + slen - hs;
404
405
    nb = strlen(label);
406
    memcpy(tmp + 20, label, nb);
407
    memcpy(tmp + 20 + nb, random, rlen);
408
    nb += rlen;
409
410
    /*
411
     * First compute P_md5(secret,label+random)[0..dlen]
412
     */
413
    if ((md_info = mbedtls_md_info_from_type(MBEDTLS_MD_MD5)) == NULL) {
414
        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
415
        goto exit;
416
    }
417
418
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
419
        goto exit;
420
    }
421
422
    ret = mbedtls_md_hmac_starts(&md_ctx, S1, hs);
423
    if (ret != 0) {
424
        goto exit;
425
    }
426
    ret = mbedtls_md_hmac_update(&md_ctx, tmp + 20, nb);
427
    if (ret != 0) {
428
        goto exit;
429
    }
430
    ret = mbedtls_md_hmac_finish(&md_ctx, 4 + tmp);
431
    if (ret != 0) {
432
        goto exit;
433
    }
434
435
    for (i = 0; i < dlen; i += 16) {
436
        ret = mbedtls_md_hmac_reset(&md_ctx);
437
        if (ret != 0) {
438
            goto exit;
439
        }
440
        ret = mbedtls_md_hmac_update(&md_ctx, 4 + tmp, 16 + nb);
441
        if (ret != 0) {
442
            goto exit;
443
        }
444
        ret = mbedtls_md_hmac_finish(&md_ctx, h_i);
445
        if (ret != 0) {
446
            goto exit;
447
        }
448
449
        ret = mbedtls_md_hmac_reset(&md_ctx);
450
        if (ret != 0) {
451
            goto exit;
452
        }
453
        ret = mbedtls_md_hmac_update(&md_ctx, 4 + tmp, 16);
454
        if (ret != 0) {
455
            goto exit;
456
        }
457
        ret = mbedtls_md_hmac_finish(&md_ctx, 4 + tmp);
458
        if (ret != 0) {
459
            goto exit;
460
        }
461
462
        k = (i + 16 > dlen) ? dlen % 16 : 16;
463
464
        for (j = 0; j < k; j++) {
465
            dstbuf[i + j]  = h_i[j];
466
        }
467
    }
468
469
    mbedtls_md_free(&md_ctx);
470
471
    /*
472
     * XOR out with P_sha1(secret,label+random)[0..dlen]
473
     */
474
    if ((md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1)) == NULL) {
475
        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
476
        goto exit;
477
    }
478
479
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
480
        goto exit;
481
    }
482
483
    ret = mbedtls_md_hmac_starts(&md_ctx, S2, hs);
484
    if (ret != 0) {
485
        goto exit;
486
    }
487
    ret = mbedtls_md_hmac_update(&md_ctx, tmp + 20, nb);
488
    if (ret != 0) {
489
        goto exit;
490
    }
491
    ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
492
    if (ret != 0) {
493
        goto exit;
494
    }
495
496
    for (i = 0; i < dlen; i += 20) {
497
        ret = mbedtls_md_hmac_reset(&md_ctx);
498
        if (ret != 0) {
499
            goto exit;
500
        }
501
        ret = mbedtls_md_hmac_update(&md_ctx, tmp, 20 + nb);
502
        if (ret != 0) {
503
            goto exit;
504
        }
505
        ret = mbedtls_md_hmac_finish(&md_ctx, h_i);
506
        if (ret != 0) {
507
            goto exit;
508
        }
509
510
        ret = mbedtls_md_hmac_reset(&md_ctx);
511
        if (ret != 0) {
512
            goto exit;
513
        }
514
        ret = mbedtls_md_hmac_update(&md_ctx, tmp, 20);
515
        if (ret != 0) {
516
            goto exit;
517
        }
518
        ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
519
        if (ret != 0) {
520
            goto exit;
521
        }
522
523
        k = (i + 20 > dlen) ? dlen % 20 : 20;
524
525
        for (j = 0; j < k; j++) {
526
            dstbuf[i + j] = (unsigned char) (dstbuf[i + j] ^ h_i[j]);
527
        }
528
    }
529
530
exit:
531
    mbedtls_md_free(&md_ctx);
532
533
    mbedtls_platform_zeroize(tmp, tmp_len);
534
    mbedtls_platform_zeroize(h_i, sizeof(h_i));
535
536
    mbedtls_free(tmp);
537
    return ret;
538
}
539
#endif /* MBEDTLS_SSL_PROTO_TLS1) || MBEDTLS_SSL_PROTO_TLS1_1 */
540
541
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
542
#if defined(MBEDTLS_USE_PSA_CRYPTO)
543
544
static psa_status_t setup_psa_key_derivation(psa_key_derivation_operation_t *derivation,
545
                                             psa_key_id_t key,
546
                                             psa_algorithm_t alg,
547
                                             const unsigned char *seed, size_t seed_length,
548
                                             const unsigned char *label, size_t label_length,
549
                                             size_t capacity)
550
{
551
    psa_status_t status;
552
553
    status = psa_key_derivation_setup(derivation, alg);
554
    if (status != PSA_SUCCESS) {
555
        return status;
556
    }
557
558
    if (PSA_ALG_IS_TLS12_PRF(alg) || PSA_ALG_IS_TLS12_PSK_TO_MS(alg)) {
559
        status = psa_key_derivation_input_bytes(derivation,
560
                                                PSA_KEY_DERIVATION_INPUT_SEED,
561
                                                seed, seed_length);
562
        if (status != PSA_SUCCESS) {
563
            return status;
564
        }
565
566
        if (mbedtls_svc_key_id_is_null(key)) {
567
            status = psa_key_derivation_input_bytes(
568
                derivation, PSA_KEY_DERIVATION_INPUT_SECRET,
569
                NULL, 0);
570
        } else {
571
            status = psa_key_derivation_input_key(
572
                derivation, PSA_KEY_DERIVATION_INPUT_SECRET, key);
573
        }
574
        if (status != PSA_SUCCESS) {
575
            return status;
576
        }
577
578
        status = psa_key_derivation_input_bytes(derivation,
579
                                                PSA_KEY_DERIVATION_INPUT_LABEL,
580
                                                label, label_length);
581
        if (status != PSA_SUCCESS) {
582
            return status;
583
        }
584
    } else {
585
        return PSA_ERROR_NOT_SUPPORTED;
586
    }
587
588
    status = psa_key_derivation_set_capacity(derivation, capacity);
589
    if (status != PSA_SUCCESS) {
590
        return status;
591
    }
592
593
    return PSA_SUCCESS;
594
}
595
596
MBEDTLS_CHECK_RETURN_CRITICAL
597
static int tls_prf_generic(mbedtls_md_type_t md_type,
598
                           const unsigned char *secret, size_t slen,
599
                           const char *label,
600
                           const unsigned char *random, size_t rlen,
601
                           unsigned char *dstbuf, size_t dlen)
602
{
603
    psa_status_t status;
604
    psa_algorithm_t alg;
605
    psa_key_id_t master_key = MBEDTLS_SVC_KEY_ID_INIT;
606
    psa_key_derivation_operation_t derivation =
607
        PSA_KEY_DERIVATION_OPERATION_INIT;
608
609
    if (md_type == MBEDTLS_MD_SHA384) {
610
        alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_384);
611
    } else {
612
        alg = PSA_ALG_TLS12_PRF(PSA_ALG_SHA_256);
613
    }
614
615
    /* Normally a "secret" should be long enough to be impossible to
616
     * find by brute force, and in particular should not be empty. But
617
     * this PRF is also used to derive an IV, in particular in EAP-TLS,
618
     * and for this use case it makes sense to have a 0-length "secret".
619
     * Since the key API doesn't allow importing a key of length 0,
620
     * keep master_key=0, which setup_psa_key_derivation() understands
621
     * to mean a 0-length "secret" input. */
622
    if (slen != 0) {
623
        psa_key_attributes_t key_attributes = psa_key_attributes_init();
624
        psa_set_key_usage_flags(&key_attributes, PSA_KEY_USAGE_DERIVE);
625
        psa_set_key_algorithm(&key_attributes, alg);
626
        psa_set_key_type(&key_attributes, PSA_KEY_TYPE_DERIVE);
627
628
        status = psa_import_key(&key_attributes, secret, slen, &master_key);
629
        if (status != PSA_SUCCESS) {
630
            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
631
        }
632
    }
633
634
    status = setup_psa_key_derivation(&derivation,
635
                                      master_key, alg,
636
                                      random, rlen,
637
                                      (unsigned char const *) label,
638
                                      (size_t) strlen(label),
639
                                      dlen);
640
    if (status != PSA_SUCCESS) {
641
        psa_key_derivation_abort(&derivation);
642
        psa_destroy_key(master_key);
643
        return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
644
    }
645
646
    status = psa_key_derivation_output_bytes(&derivation, dstbuf, dlen);
647
    if (status != PSA_SUCCESS) {
648
        psa_key_derivation_abort(&derivation);
649
        psa_destroy_key(master_key);
650
        return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
651
    }
652
653
    status = psa_key_derivation_abort(&derivation);
654
    if (status != PSA_SUCCESS) {
655
        psa_destroy_key(master_key);
656
        return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
657
    }
658
659
    if (!mbedtls_svc_key_id_is_null(master_key)) {
660
        status = psa_destroy_key(master_key);
661
    }
662
    if (status != PSA_SUCCESS) {
663
        return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
664
    }
665
666
    return 0;
667
}
668
669
#else /* MBEDTLS_USE_PSA_CRYPTO */
670
671
MBEDTLS_CHECK_RETURN_CRITICAL
672
static int tls_prf_generic(mbedtls_md_type_t md_type,
673
                           const unsigned char *secret, size_t slen,
674
                           const char *label,
675
                           const unsigned char *random, size_t rlen,
676
                           unsigned char *dstbuf, size_t dlen)
677
0
{
678
0
    size_t nb;
679
0
    size_t i, j, k, md_len;
680
0
    unsigned char *tmp;
681
0
    size_t tmp_len = 0;
682
0
    unsigned char h_i[MBEDTLS_MD_MAX_SIZE];
683
0
    const mbedtls_md_info_t *md_info;
684
0
    mbedtls_md_context_t md_ctx;
685
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
686
687
0
    mbedtls_md_init(&md_ctx);
688
689
0
    if ((md_info = mbedtls_md_info_from_type(md_type)) == NULL) {
690
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
691
0
    }
692
693
0
    md_len = mbedtls_md_get_size(md_info);
694
695
0
    tmp_len = md_len + strlen(label) + rlen;
696
0
    tmp = mbedtls_calloc(1, tmp_len);
697
0
    if (tmp == NULL) {
698
0
        ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
699
0
        goto exit;
700
0
    }
701
702
0
    nb = strlen(label);
703
0
    memcpy(tmp + md_len, label, nb);
704
0
    memcpy(tmp + md_len + nb, random, rlen);
705
0
    nb += rlen;
706
707
    /*
708
     * Compute P_<hash>(secret, label + random)[0..dlen]
709
     */
710
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 1)) != 0) {
711
0
        goto exit;
712
0
    }
713
714
0
    ret = mbedtls_md_hmac_starts(&md_ctx, secret, slen);
715
0
    if (ret != 0) {
716
0
        goto exit;
717
0
    }
718
0
    ret = mbedtls_md_hmac_update(&md_ctx, tmp + md_len, nb);
719
0
    if (ret != 0) {
720
0
        goto exit;
721
0
    }
722
0
    ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
723
0
    if (ret != 0) {
724
0
        goto exit;
725
0
    }
726
727
0
    for (i = 0; i < dlen; i += md_len) {
728
0
        ret = mbedtls_md_hmac_reset(&md_ctx);
729
0
        if (ret != 0) {
730
0
            goto exit;
731
0
        }
732
0
        ret = mbedtls_md_hmac_update(&md_ctx, tmp, md_len + nb);
733
0
        if (ret != 0) {
734
0
            goto exit;
735
0
        }
736
0
        ret = mbedtls_md_hmac_finish(&md_ctx, h_i);
737
0
        if (ret != 0) {
738
0
            goto exit;
739
0
        }
740
741
0
        ret = mbedtls_md_hmac_reset(&md_ctx);
742
0
        if (ret != 0) {
743
0
            goto exit;
744
0
        }
745
0
        ret = mbedtls_md_hmac_update(&md_ctx, tmp, md_len);
746
0
        if (ret != 0) {
747
0
            goto exit;
748
0
        }
749
0
        ret = mbedtls_md_hmac_finish(&md_ctx, tmp);
750
0
        if (ret != 0) {
751
0
            goto exit;
752
0
        }
753
754
0
        k = (i + md_len > dlen) ? dlen % md_len : md_len;
755
756
0
        for (j = 0; j < k; j++) {
757
0
            dstbuf[i + j]  = h_i[j];
758
0
        }
759
0
    }
760
761
0
exit:
762
0
    mbedtls_md_free(&md_ctx);
763
764
0
    if (tmp != NULL) {
765
0
        mbedtls_platform_zeroize(tmp, tmp_len);
766
0
    }
767
768
0
    mbedtls_platform_zeroize(h_i, sizeof(h_i));
769
770
0
    mbedtls_free(tmp);
771
772
0
    return ret;
773
0
}
774
#endif /* MBEDTLS_USE_PSA_CRYPTO */
775
#if defined(MBEDTLS_SHA256_C)
776
MBEDTLS_CHECK_RETURN_CRITICAL
777
static int tls_prf_sha256(const unsigned char *secret, size_t slen,
778
                          const char *label,
779
                          const unsigned char *random, size_t rlen,
780
                          unsigned char *dstbuf, size_t dlen)
781
0
{
782
0
    return tls_prf_generic(MBEDTLS_MD_SHA256, secret, slen,
783
0
                           label, random, rlen, dstbuf, dlen);
784
0
}
785
#endif /* MBEDTLS_SHA256_C */
786
787
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
788
MBEDTLS_CHECK_RETURN_CRITICAL
789
static int tls_prf_sha384(const unsigned char *secret, size_t slen,
790
                          const char *label,
791
                          const unsigned char *random, size_t rlen,
792
                          unsigned char *dstbuf, size_t dlen)
793
{
794
    return tls_prf_generic(MBEDTLS_MD_SHA384, secret, slen,
795
                           label, random, rlen, dstbuf, dlen);
796
}
797
#endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
798
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
799
800
static void ssl_update_checksum_start(mbedtls_ssl_context *, const unsigned char *, size_t);
801
802
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
803
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
804
static void ssl_update_checksum_md5sha1(mbedtls_ssl_context *, const unsigned char *, size_t);
805
#endif
806
807
#if defined(MBEDTLS_SSL_PROTO_SSL3)
808
static void ssl_calc_verify_ssl(const mbedtls_ssl_context *, unsigned char *, size_t *);
809
static void ssl_calc_finished_ssl(mbedtls_ssl_context *, unsigned char *, int);
810
#endif
811
812
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
813
static void ssl_calc_verify_tls(const mbedtls_ssl_context *, unsigned char *, size_t *);
814
static void ssl_calc_finished_tls(mbedtls_ssl_context *, unsigned char *, int);
815
#endif
816
817
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
818
#if defined(MBEDTLS_SHA256_C)
819
static void ssl_update_checksum_sha256(mbedtls_ssl_context *, const unsigned char *, size_t);
820
static void ssl_calc_verify_tls_sha256(const mbedtls_ssl_context *, unsigned char *, size_t *);
821
static void ssl_calc_finished_tls_sha256(mbedtls_ssl_context *, unsigned char *, int);
822
#endif
823
824
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
825
static void ssl_update_checksum_sha384(mbedtls_ssl_context *, const unsigned char *, size_t);
826
static void ssl_calc_verify_tls_sha384(const mbedtls_ssl_context *, unsigned char *, size_t *);
827
static void ssl_calc_finished_tls_sha384(mbedtls_ssl_context *, unsigned char *, int);
828
#endif
829
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
830
831
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) && \
832
    defined(MBEDTLS_USE_PSA_CRYPTO)
833
MBEDTLS_CHECK_RETURN_CRITICAL
834
static int ssl_use_opaque_psk(mbedtls_ssl_context const *ssl)
835
{
836
    if (ssl->conf->f_psk != NULL) {
837
        /* If we've used a callback to select the PSK,
838
         * the static configuration is irrelevant. */
839
        if (!mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque)) {
840
            return 1;
841
        }
842
843
        return 0;
844
    }
845
846
    if (!mbedtls_svc_key_id_is_null(ssl->conf->psk_opaque)) {
847
        return 1;
848
    }
849
850
    return 0;
851
}
852
#endif /* MBEDTLS_USE_PSA_CRYPTO &&
853
          MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
854
855
#if defined(MBEDTLS_SSL_EXPORT_KEYS)
856
static mbedtls_tls_prf_types tls_prf_get_type(mbedtls_ssl_tls_prf_cb *tls_prf)
857
0
{
858
#if defined(MBEDTLS_SSL_PROTO_SSL3)
859
    if (tls_prf == ssl3_prf) {
860
        return MBEDTLS_SSL_TLS_PRF_SSL3;
861
    } else
862
#endif
863
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
864
    if (tls_prf == tls1_prf) {
865
        return MBEDTLS_SSL_TLS_PRF_TLS1;
866
    } else
867
#endif
868
0
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
869
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
870
    if (tls_prf == tls_prf_sha384) {
871
        return MBEDTLS_SSL_TLS_PRF_SHA384;
872
    } else
873
#endif
874
0
#if defined(MBEDTLS_SHA256_C)
875
0
    if (tls_prf == tls_prf_sha256) {
876
0
        return MBEDTLS_SSL_TLS_PRF_SHA256;
877
0
    } else
878
0
#endif
879
0
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
880
0
    return MBEDTLS_SSL_TLS_PRF_NONE;
881
0
}
882
#endif /* MBEDTLS_SSL_EXPORT_KEYS */
883
884
int  mbedtls_ssl_tls_prf(const mbedtls_tls_prf_types prf,
885
                         const unsigned char *secret, size_t slen,
886
                         const char *label,
887
                         const unsigned char *random, size_t rlen,
888
                         unsigned char *dstbuf, size_t dlen)
889
0
{
890
0
    mbedtls_ssl_tls_prf_cb *tls_prf = NULL;
891
892
0
    switch (prf) {
893
#if defined(MBEDTLS_SSL_PROTO_SSL3)
894
        case MBEDTLS_SSL_TLS_PRF_SSL3:
895
            tls_prf = ssl3_prf;
896
            break;
897
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
898
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
899
        case MBEDTLS_SSL_TLS_PRF_TLS1:
900
            tls_prf = tls1_prf;
901
            break;
902
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
903
904
0
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
905
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
906
        case MBEDTLS_SSL_TLS_PRF_SHA384:
907
            tls_prf = tls_prf_sha384;
908
            break;
909
#endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
910
0
#if defined(MBEDTLS_SHA256_C)
911
0
        case MBEDTLS_SSL_TLS_PRF_SHA256:
912
0
            tls_prf = tls_prf_sha256;
913
0
            break;
914
0
#endif /* MBEDTLS_SHA256_C */
915
0
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
916
0
        default:
917
0
            return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
918
0
    }
919
920
0
    return tls_prf(secret, slen, label, random, rlen, dstbuf, dlen);
921
0
}
922
923
/* Type for the TLS PRF */
924
typedef int ssl_tls_prf_t(const unsigned char *, size_t, const char *,
925
                          const unsigned char *, size_t,
926
                          unsigned char *, size_t);
927
928
/*
929
 * Populate a transform structure with session keys and all the other
930
 * necessary information.
931
 *
932
 * Parameters:
933
 * - [in/out]: transform: structure to populate
934
 *      [in] must be just initialised with mbedtls_ssl_transform_init()
935
 *      [out] fully populated, ready for use by mbedtls_ssl_{en,de}crypt_buf()
936
 * - [in] ciphersuite
937
 * - [in] master
938
 * - [in] encrypt_then_mac
939
 * - [in] trunc_hmac
940
 * - [in] compression
941
 * - [in] tls_prf: pointer to PRF to use for key derivation
942
 * - [in] randbytes: buffer holding ServerHello.random + ClientHello.random
943
 * - [in] minor_ver: SSL/TLS minor version
944
 * - [in] endpoint: client or server
945
 * - [in] ssl: optionally used for:
946
 *        - MBEDTLS_SSL_HW_RECORD_ACCEL: whole context (non-const)
947
 *        - MBEDTLS_SSL_EXPORT_KEYS: ssl->conf->{f,p}_export_keys
948
 *        - MBEDTLS_DEBUG_C: ssl->conf->{f,p}_dbg
949
 */
950
MBEDTLS_CHECK_RETURN_CRITICAL
951
static int ssl_populate_transform(mbedtls_ssl_transform *transform,
952
                                  int ciphersuite,
953
                                  const unsigned char master[48],
954
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
955
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
956
                                  int encrypt_then_mac,
957
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
958
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
959
                                  int trunc_hmac,
960
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
961
#endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
962
#if defined(MBEDTLS_ZLIB_SUPPORT)
963
                                  int compression,
964
#endif
965
                                  ssl_tls_prf_t tls_prf,
966
                                  const unsigned char randbytes[64],
967
                                  int minor_ver,
968
                                  unsigned endpoint,
969
#if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
970
                                  const
971
#endif
972
                                  mbedtls_ssl_context *ssl)
973
0
{
974
0
    int ret = 0;
975
#if defined(MBEDTLS_USE_PSA_CRYPTO)
976
    int psa_fallthrough;
977
#endif /* MBEDTLS_USE_PSA_CRYPTO */
978
0
    int do_mbedtls_cipher_setup;
979
0
    unsigned char keyblk[256];
980
0
    unsigned char *key1;
981
0
    unsigned char *key2;
982
0
    unsigned char *mac_enc;
983
0
    unsigned char *mac_dec;
984
0
    size_t mac_key_len = 0;
985
0
    size_t iv_copy_len;
986
0
    unsigned keylen;
987
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info;
988
0
    const mbedtls_cipher_info_t *cipher_info;
989
0
    const mbedtls_md_info_t *md_info;
990
991
#if !defined(MBEDTLS_SSL_HW_RECORD_ACCEL) && \
992
    !defined(MBEDTLS_SSL_EXPORT_KEYS) && \
993
    !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
994
    !defined(MBEDTLS_DEBUG_C)
995
    ssl = NULL; /* make sure we don't use it except for those cases */
996
    (void) ssl;
997
#endif
998
999
    /*
1000
     * Some data just needs copying into the structure
1001
     */
1002
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \
1003
    defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1004
    transform->encrypt_then_mac = encrypt_then_mac;
1005
#endif
1006
0
    transform->minor_ver = minor_ver;
1007
1008
#if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
1009
    memcpy(transform->randbytes, randbytes, sizeof(transform->randbytes));
1010
#endif
1011
1012
    /*
1013
     * Get various info structures
1014
     */
1015
0
    ciphersuite_info = mbedtls_ssl_ciphersuite_from_id(ciphersuite);
1016
0
    if (ciphersuite_info == NULL) {
1017
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("ciphersuite info for %d not found",
1018
0
                                  ciphersuite));
1019
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1020
0
    }
1021
1022
0
    cipher_info = mbedtls_cipher_info_from_type(ciphersuite_info->cipher);
1023
0
    if (cipher_info == NULL) {
1024
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("cipher info for %u not found",
1025
0
                                  ciphersuite_info->cipher));
1026
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1027
0
    }
1028
1029
0
    md_info = mbedtls_md_info_from_type(ciphersuite_info->mac);
1030
0
    if (md_info == NULL) {
1031
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("mbedtls_md info for %u not found",
1032
0
                                  (unsigned) ciphersuite_info->mac));
1033
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1034
0
    }
1035
1036
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
1037
    /* Copy own and peer's CID if the use of the CID
1038
     * extension has been negotiated. */
1039
    if (ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_ENABLED) {
1040
        MBEDTLS_SSL_DEBUG_MSG(3, ("Copy CIDs into SSL transform"));
1041
1042
        transform->in_cid_len = ssl->own_cid_len;
1043
        memcpy(transform->in_cid, ssl->own_cid, ssl->own_cid_len);
1044
        MBEDTLS_SSL_DEBUG_BUF(3, "Incoming CID", transform->in_cid,
1045
                              transform->in_cid_len);
1046
1047
        transform->out_cid_len = ssl->handshake->peer_cid_len;
1048
        memcpy(transform->out_cid, ssl->handshake->peer_cid,
1049
               ssl->handshake->peer_cid_len);
1050
        MBEDTLS_SSL_DEBUG_BUF(3, "Outgoing CID", transform->out_cid,
1051
                              transform->out_cid_len);
1052
    }
1053
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
1054
1055
    /*
1056
     * Compute key block using the PRF
1057
     */
1058
0
    ret = tls_prf(master, 48, "key expansion", randbytes, 64, keyblk, 256);
1059
0
    if (ret != 0) {
1060
0
        MBEDTLS_SSL_DEBUG_RET(1, "prf", ret);
1061
0
        return ret;
1062
0
    }
1063
1064
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("ciphersuite = %s",
1065
0
                              mbedtls_ssl_get_ciphersuite_name(ciphersuite)));
1066
0
    MBEDTLS_SSL_DEBUG_BUF(3, "master secret", master, 48);
1067
0
    MBEDTLS_SSL_DEBUG_BUF(4, "random bytes", randbytes, 64);
1068
0
    MBEDTLS_SSL_DEBUG_BUF(4, "key block", keyblk, 256);
1069
1070
    /*
1071
     * Determine the appropriate key, IV and MAC length.
1072
     */
1073
1074
0
    keylen = cipher_info->key_bitlen / 8;
1075
1076
0
#if defined(MBEDTLS_GCM_C) ||                           \
1077
0
    defined(MBEDTLS_CCM_C) ||                           \
1078
0
    defined(MBEDTLS_CHACHAPOLY_C)
1079
0
    if (cipher_info->mode == MBEDTLS_MODE_GCM ||
1080
0
        cipher_info->mode == MBEDTLS_MODE_CCM ||
1081
0
        cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY) {
1082
0
        size_t explicit_ivlen;
1083
1084
0
        transform->maclen = 0;
1085
0
        mac_key_len = 0;
1086
0
        transform->taglen =
1087
0
            ciphersuite_info->flags & MBEDTLS_CIPHERSUITE_SHORT_TAG ? 8 : 16;
1088
1089
        /* All modes haves 96-bit IVs, but the length of the static parts vary
1090
         * with mode and version:
1091
         * - For GCM and CCM in TLS 1.2, there's a static IV of 4 Bytes
1092
         *   (to be concatenated with a dynamically chosen IV of 8 Bytes)
1093
         * - For ChaChaPoly in TLS 1.2, and all modes in TLS 1.3, there's
1094
         *   a static IV of 12 Bytes (to be XOR'ed with the 8 Byte record
1095
         *   sequence number).
1096
         */
1097
0
        transform->ivlen = 12;
1098
#if defined(MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL)
1099
        if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_4) {
1100
            transform->fixed_ivlen = 12;
1101
        } else
1102
#endif /* MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL */
1103
0
        {
1104
0
            if (cipher_info->mode == MBEDTLS_MODE_CHACHAPOLY) {
1105
0
                transform->fixed_ivlen = 12;
1106
0
            } else {
1107
0
                transform->fixed_ivlen = 4;
1108
0
            }
1109
0
        }
1110
1111
        /* Minimum length of encrypted record */
1112
0
        explicit_ivlen = transform->ivlen - transform->fixed_ivlen;
1113
0
        transform->minlen = explicit_ivlen + transform->taglen;
1114
0
    } else
1115
0
#endif /* MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C */
1116
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1117
    if (cipher_info->mode == MBEDTLS_MODE_STREAM ||
1118
        cipher_info->mode == MBEDTLS_MODE_CBC) {
1119
        /* Initialize HMAC contexts */
1120
        if ((ret = mbedtls_md_setup(&transform->md_ctx_enc, md_info, 1)) != 0 ||
1121
            (ret = mbedtls_md_setup(&transform->md_ctx_dec, md_info, 1)) != 0) {
1122
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_setup", ret);
1123
            goto end;
1124
        }
1125
1126
        /* Get MAC length */
1127
        mac_key_len = mbedtls_md_get_size(md_info);
1128
        transform->maclen = mac_key_len;
1129
1130
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1131
        /*
1132
         * If HMAC is to be truncated, we shall keep the leftmost bytes,
1133
         * (rfc 6066 page 13 or rfc 2104 section 4),
1134
         * so we only need to adjust the length here.
1135
         */
1136
        if (trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED) {
1137
            transform->maclen = MBEDTLS_SSL_TRUNCATED_HMAC_LEN;
1138
1139
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT)
1140
            /* Fall back to old, non-compliant version of the truncated
1141
             * HMAC implementation which also truncates the key
1142
             * (Mbed TLS versions from 1.3 to 2.6.0) */
1143
            mac_key_len = transform->maclen;
1144
#endif
1145
        }
1146
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1147
1148
        /* IV length */
1149
        transform->ivlen = cipher_info->iv_size;
1150
1151
        /* Minimum length */
1152
        if (cipher_info->mode == MBEDTLS_MODE_STREAM) {
1153
            transform->minlen = transform->maclen;
1154
        } else {
1155
            /*
1156
             * GenericBlockCipher:
1157
             * 1. if EtM is in use: one block plus MAC
1158
             *    otherwise: * first multiple of blocklen greater than maclen
1159
             * 2. IV except for SSL3 and TLS 1.0
1160
             */
1161
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1162
            if (encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED) {
1163
                transform->minlen = transform->maclen
1164
                                    + cipher_info->block_size;
1165
            } else
1166
#endif
1167
            {
1168
                transform->minlen = transform->maclen
1169
                                    + cipher_info->block_size
1170
                                    - transform->maclen % cipher_info->block_size;
1171
            }
1172
1173
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1)
1174
            if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ||
1175
                minor_ver == MBEDTLS_SSL_MINOR_VERSION_1) {
1176
                ; /* No need to adjust minlen */
1177
            } else
1178
#endif
1179
#if defined(MBEDTLS_SSL_PROTO_TLS1_1) || defined(MBEDTLS_SSL_PROTO_TLS1_2)
1180
            if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_2 ||
1181
                minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1182
                transform->minlen += transform->ivlen;
1183
            } else
1184
#endif
1185
            {
1186
                MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1187
                ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1188
                goto end;
1189
            }
1190
        }
1191
    } else
1192
#endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1193
0
    {
1194
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1195
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1196
0
    }
1197
1198
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("keylen: %u, minlen: %u, ivlen: %u, maclen: %u",
1199
0
                              (unsigned) keylen,
1200
0
                              (unsigned) transform->minlen,
1201
0
                              (unsigned) transform->ivlen,
1202
0
                              (unsigned) transform->maclen));
1203
1204
    /*
1205
     * Finally setup the cipher contexts, IVs and MAC secrets.
1206
     */
1207
0
#if defined(MBEDTLS_SSL_CLI_C)
1208
0
    if (endpoint == MBEDTLS_SSL_IS_CLIENT) {
1209
0
        key1 = keyblk + mac_key_len * 2;
1210
0
        key2 = keyblk + mac_key_len * 2 + keylen;
1211
1212
0
        mac_enc = keyblk;
1213
0
        mac_dec = keyblk + mac_key_len;
1214
1215
        /*
1216
         * This is not used in TLS v1.1.
1217
         */
1218
0
        iv_copy_len = (transform->fixed_ivlen) ?
1219
0
                      transform->fixed_ivlen : transform->ivlen;
1220
0
        memcpy(transform->iv_enc, key2 + keylen,  iv_copy_len);
1221
0
        memcpy(transform->iv_dec, key2 + keylen + iv_copy_len,
1222
0
               iv_copy_len);
1223
0
    } else
1224
0
#endif /* MBEDTLS_SSL_CLI_C */
1225
0
#if defined(MBEDTLS_SSL_SRV_C)
1226
0
    if (endpoint == MBEDTLS_SSL_IS_SERVER) {
1227
0
        key1 = keyblk + mac_key_len * 2 + keylen;
1228
0
        key2 = keyblk + mac_key_len * 2;
1229
1230
0
        mac_enc = keyblk + mac_key_len;
1231
0
        mac_dec = keyblk;
1232
1233
        /*
1234
         * This is not used in TLS v1.1.
1235
         */
1236
0
        iv_copy_len = (transform->fixed_ivlen) ?
1237
0
                      transform->fixed_ivlen : transform->ivlen;
1238
0
        memcpy(transform->iv_dec, key1 + keylen,  iv_copy_len);
1239
0
        memcpy(transform->iv_enc, key1 + keylen + iv_copy_len,
1240
0
               iv_copy_len);
1241
0
    } else
1242
0
#endif /* MBEDTLS_SSL_SRV_C */
1243
0
    {
1244
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1245
0
        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1246
0
        goto end;
1247
0
    }
1248
1249
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1250
#if defined(MBEDTLS_SSL_PROTO_SSL3)
1251
    if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
1252
        if (mac_key_len > sizeof(transform->mac_enc)) {
1253
            MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1254
            ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1255
            goto end;
1256
        }
1257
1258
        memcpy(transform->mac_enc, mac_enc, mac_key_len);
1259
        memcpy(transform->mac_dec, mac_dec, mac_key_len);
1260
    } else
1261
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1262
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
1263
    defined(MBEDTLS_SSL_PROTO_TLS1_2)
1264
    if (minor_ver >= MBEDTLS_SSL_MINOR_VERSION_1) {
1265
        /* For HMAC-based ciphersuites, initialize the HMAC transforms.
1266
           For AEAD-based ciphersuites, there is nothing to do here. */
1267
        if (mac_key_len != 0) {
1268
            ret = mbedtls_md_hmac_starts(&transform->md_ctx_enc,
1269
                                         mac_enc, mac_key_len);
1270
            if (ret != 0) {
1271
                goto end;
1272
            }
1273
            ret = mbedtls_md_hmac_starts(&transform->md_ctx_dec,
1274
                                         mac_dec, mac_key_len);
1275
            if (ret != 0) {
1276
                goto end;
1277
            }
1278
        }
1279
    } else
1280
#endif
1281
    {
1282
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1283
        ret = MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1284
        goto end;
1285
    }
1286
#endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1287
1288
#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
1289
    if (mbedtls_ssl_hw_record_init != NULL) {
1290
        ret = 0;
1291
1292
        MBEDTLS_SSL_DEBUG_MSG(2, ("going for mbedtls_ssl_hw_record_init()"));
1293
1294
        if ((ret = mbedtls_ssl_hw_record_init(ssl, key1, key2, keylen,
1295
                                              transform->iv_enc, transform->iv_dec,
1296
                                              iv_copy_len,
1297
                                              mac_enc, mac_dec,
1298
                                              mac_key_len)) != 0) {
1299
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_hw_record_init", ret);
1300
            ret = MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
1301
            goto end;
1302
        }
1303
    }
1304
#else
1305
0
    ((void) mac_dec);
1306
0
    ((void) mac_enc);
1307
0
#endif /* MBEDTLS_SSL_HW_RECORD_ACCEL */
1308
1309
0
#if defined(MBEDTLS_SSL_EXPORT_KEYS)
1310
0
    if (ssl->conf->f_export_keys != NULL) {
1311
0
        ssl->conf->f_export_keys(ssl->conf->p_export_keys,
1312
0
                                 master, keyblk,
1313
0
                                 mac_key_len, keylen,
1314
0
                                 iv_copy_len);
1315
0
    }
1316
1317
0
    if (ssl->conf->f_export_keys_ext != NULL) {
1318
0
        ssl->conf->f_export_keys_ext(ssl->conf->p_export_keys,
1319
0
                                     master, keyblk,
1320
0
                                     mac_key_len, keylen,
1321
0
                                     iv_copy_len,
1322
0
                                     randbytes + 32,
1323
0
                                     randbytes,
1324
0
                                     tls_prf_get_type(tls_prf));
1325
0
    }
1326
0
#endif
1327
1328
0
    do_mbedtls_cipher_setup = 1;
1329
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1330
1331
    /* Only use PSA-based ciphers for TLS-1.2.
1332
     * That's relevant at least for TLS-1.0, where
1333
     * we assume that mbedtls_cipher_crypt() updates
1334
     * the structure field for the IV, which the PSA-based
1335
     * implementation currently doesn't. */
1336
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1337
    if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1338
        ret = mbedtls_cipher_setup_psa(&transform->cipher_ctx_enc,
1339
                                       cipher_info, transform->taglen);
1340
        if (ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) {
1341
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup_psa", ret);
1342
            goto end;
1343
        }
1344
1345
        if (ret == 0) {
1346
            MBEDTLS_SSL_DEBUG_MSG(3, ("Successfully setup PSA-based encryption cipher context"));
1347
            psa_fallthrough = 0;
1348
        } else {
1349
            MBEDTLS_SSL_DEBUG_MSG(1,
1350
                                  (
1351
                                      "Failed to setup PSA-based cipher context for record encryption - fall through to default setup."));
1352
            psa_fallthrough = 1;
1353
        }
1354
    } else {
1355
        psa_fallthrough = 1;
1356
    }
1357
#else
1358
    psa_fallthrough = 1;
1359
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1360
1361
    if (psa_fallthrough == 0) {
1362
        do_mbedtls_cipher_setup = 0;
1363
    }
1364
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1365
0
    if (do_mbedtls_cipher_setup &&
1366
0
        (ret = mbedtls_cipher_setup(&transform->cipher_ctx_enc,
1367
0
                                    cipher_info)) != 0) {
1368
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup", ret);
1369
0
        goto end;
1370
0
    }
1371
1372
0
    do_mbedtls_cipher_setup = 1;
1373
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1374
    /* Only use PSA-based ciphers for TLS-1.2.
1375
     * That's relevant at least for TLS-1.0, where
1376
     * we assume that mbedtls_cipher_crypt() updates
1377
     * the structure field for the IV, which the PSA-based
1378
     * implementation currently doesn't. */
1379
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1380
    if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1381
        ret = mbedtls_cipher_setup_psa(&transform->cipher_ctx_dec,
1382
                                       cipher_info, transform->taglen);
1383
        if (ret != 0 && ret != MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE) {
1384
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup_psa", ret);
1385
            goto end;
1386
        }
1387
1388
        if (ret == 0) {
1389
            MBEDTLS_SSL_DEBUG_MSG(3, ("Successfully setup PSA-based decryption cipher context"));
1390
            psa_fallthrough = 0;
1391
        } else {
1392
            MBEDTLS_SSL_DEBUG_MSG(1,
1393
                                  (
1394
                                      "Failed to setup PSA-based cipher context for record decryption - fall through to default setup."));
1395
            psa_fallthrough = 1;
1396
        }
1397
    } else {
1398
        psa_fallthrough = 1;
1399
    }
1400
#else
1401
    psa_fallthrough = 1;
1402
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1403
1404
    if (psa_fallthrough == 0) {
1405
        do_mbedtls_cipher_setup = 0;
1406
    }
1407
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1408
0
    if (do_mbedtls_cipher_setup &&
1409
0
        (ret = mbedtls_cipher_setup(&transform->cipher_ctx_dec,
1410
0
                                    cipher_info)) != 0) {
1411
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setup", ret);
1412
0
        goto end;
1413
0
    }
1414
1415
0
    if ((ret = mbedtls_cipher_setkey(&transform->cipher_ctx_enc, key1,
1416
0
                                     cipher_info->key_bitlen,
1417
0
                                     MBEDTLS_ENCRYPT)) != 0) {
1418
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setkey", ret);
1419
0
        goto end;
1420
0
    }
1421
1422
0
    if ((ret = mbedtls_cipher_setkey(&transform->cipher_ctx_dec, key2,
1423
0
                                     cipher_info->key_bitlen,
1424
0
                                     MBEDTLS_DECRYPT)) != 0) {
1425
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_setkey", ret);
1426
0
        goto end;
1427
0
    }
1428
1429
#if defined(MBEDTLS_CIPHER_MODE_CBC)
1430
    if (cipher_info->mode == MBEDTLS_MODE_CBC) {
1431
        if ((ret = mbedtls_cipher_set_padding_mode(&transform->cipher_ctx_enc,
1432
                                                   MBEDTLS_PADDING_NONE)) != 0) {
1433
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_set_padding_mode", ret);
1434
            goto end;
1435
        }
1436
1437
        if ((ret = mbedtls_cipher_set_padding_mode(&transform->cipher_ctx_dec,
1438
                                                   MBEDTLS_PADDING_NONE)) != 0) {
1439
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_cipher_set_padding_mode", ret);
1440
            goto end;
1441
        }
1442
    }
1443
#endif /* MBEDTLS_CIPHER_MODE_CBC */
1444
1445
1446
    /* Initialize Zlib contexts */
1447
#if defined(MBEDTLS_ZLIB_SUPPORT)
1448
    if (compression == MBEDTLS_SSL_COMPRESS_DEFLATE) {
1449
        MBEDTLS_SSL_DEBUG_MSG(3, ("Initializing zlib states"));
1450
1451
        memset(&transform->ctx_deflate, 0, sizeof(transform->ctx_deflate));
1452
        memset(&transform->ctx_inflate, 0, sizeof(transform->ctx_inflate));
1453
1454
        if (deflateInit(&transform->ctx_deflate,
1455
                        Z_DEFAULT_COMPRESSION)   != Z_OK ||
1456
            inflateInit(&transform->ctx_inflate) != Z_OK) {
1457
            MBEDTLS_SSL_DEBUG_MSG(1, ("Failed to initialize compression"));
1458
            ret = MBEDTLS_ERR_SSL_COMPRESSION_FAILED;
1459
            goto end;
1460
        }
1461
    }
1462
#endif /* MBEDTLS_ZLIB_SUPPORT */
1463
1464
0
end:
1465
0
    mbedtls_platform_zeroize(keyblk, sizeof(keyblk));
1466
0
    return ret;
1467
0
}
1468
1469
/*
1470
 * Set appropriate PRF function and other SSL / TLS 1.0/1.1 / TLS1.2 functions
1471
 *
1472
 * Inputs:
1473
 * - SSL/TLS minor version
1474
 * - hash associated with the ciphersuite (only used by TLS 1.2)
1475
 *
1476
 * Outputs:
1477
 * - the tls_prf, calc_verify and calc_finished members of handshake structure
1478
 */
1479
MBEDTLS_CHECK_RETURN_CRITICAL
1480
static int ssl_set_handshake_prfs(mbedtls_ssl_handshake_params *handshake,
1481
                                  int minor_ver,
1482
                                  mbedtls_md_type_t hash)
1483
0
{
1484
0
#if !defined(MBEDTLS_SSL_PROTO_TLS1_2) ||       \
1485
0
    !(defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384))
1486
0
    (void) hash;
1487
0
#endif
1488
1489
#if defined(MBEDTLS_SSL_PROTO_SSL3)
1490
    if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
1491
        handshake->tls_prf = ssl3_prf;
1492
        handshake->calc_verify = ssl_calc_verify_ssl;
1493
        handshake->calc_finished = ssl_calc_finished_ssl;
1494
    } else
1495
#endif
1496
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1497
    if (minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
1498
        handshake->tls_prf = tls1_prf;
1499
        handshake->calc_verify = ssl_calc_verify_tls;
1500
        handshake->calc_finished = ssl_calc_finished_tls;
1501
    } else
1502
#endif
1503
0
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1504
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
1505
    if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
1506
        hash == MBEDTLS_MD_SHA384) {
1507
        handshake->tls_prf = tls_prf_sha384;
1508
        handshake->calc_verify = ssl_calc_verify_tls_sha384;
1509
        handshake->calc_finished = ssl_calc_finished_tls_sha384;
1510
    } else
1511
#endif
1512
0
#if defined(MBEDTLS_SHA256_C)
1513
0
    if (minor_ver == MBEDTLS_SSL_MINOR_VERSION_3) {
1514
0
        handshake->tls_prf = tls_prf_sha256;
1515
0
        handshake->calc_verify = ssl_calc_verify_tls_sha256;
1516
0
        handshake->calc_finished = ssl_calc_finished_tls_sha256;
1517
0
    } else
1518
0
#endif
1519
0
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1520
0
    {
1521
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1522
0
    }
1523
1524
0
    return 0;
1525
0
}
1526
1527
/*
1528
 * Compute master secret if needed
1529
 *
1530
 * Parameters:
1531
 * [in/out] handshake
1532
 *          [in] resume, premaster, extended_ms, calc_verify, tls_prf
1533
 *               (PSA-PSK) ciphersuite_info, psk_opaque
1534
 *          [out] premaster (cleared)
1535
 * [out] master
1536
 * [in] ssl: optionally used for debugging, EMS and PSA-PSK
1537
 *      debug: conf->f_dbg, conf->p_dbg
1538
 *      EMS: passed to calc_verify (debug + (SSL3) session_negotiate)
1539
 *      PSA-PSA: minor_ver, conf
1540
 */
1541
MBEDTLS_CHECK_RETURN_CRITICAL
1542
static int ssl_compute_master(mbedtls_ssl_handshake_params *handshake,
1543
                              unsigned char *master,
1544
                              const mbedtls_ssl_context *ssl)
1545
0
{
1546
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1547
1548
    /* cf. RFC 5246, Section 8.1:
1549
     * "The master secret is always exactly 48 bytes in length." */
1550
0
    size_t const master_secret_len = 48;
1551
1552
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1553
    unsigned char session_hash[48];
1554
#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
1555
1556
    /* The label for the KDF used for key expansion.
1557
     * This is either "master secret" or "extended master secret"
1558
     * depending on whether the Extended Master Secret extension
1559
     * is used. */
1560
0
    char const *lbl = "master secret";
1561
1562
    /* The salt for the KDF used for key expansion.
1563
     * - If the Extended Master Secret extension is not used,
1564
     *   this is ClientHello.Random + ServerHello.Random
1565
     *   (see Sect. 8.1 in RFC 5246).
1566
     * - If the Extended Master Secret extension is used,
1567
     *   this is the transcript of the handshake so far.
1568
     *   (see Sect. 4 in RFC 7627). */
1569
0
    unsigned char const *salt = handshake->randbytes;
1570
0
    size_t salt_len = 64;
1571
1572
0
#if !defined(MBEDTLS_DEBUG_C) &&                    \
1573
0
    !defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \
1574
0
    !(defined(MBEDTLS_USE_PSA_CRYPTO) &&            \
1575
0
    defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED))
1576
0
    ssl = NULL; /* make sure we don't use it except for those cases */
1577
0
    (void) ssl;
1578
0
#endif
1579
1580
0
    if (handshake->resume != 0) {
1581
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("no premaster (session resumed)"));
1582
0
        return 0;
1583
0
    }
1584
1585
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
1586
    if (handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED) {
1587
        lbl  = "extended master secret";
1588
        salt = session_hash;
1589
        handshake->calc_verify(ssl, session_hash, &salt_len);
1590
1591
        MBEDTLS_SSL_DEBUG_BUF(3, "session hash for extended master secret",
1592
                              session_hash, salt_len);
1593
    }
1594
#endif /* MBEDTLS_SSL_EXTENDED_MS_ENABLED */
1595
1596
#if defined(MBEDTLS_USE_PSA_CRYPTO) &&          \
1597
    defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1598
    if (handshake->ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK &&
1599
        ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 &&
1600
        ssl_use_opaque_psk(ssl) == 1) {
1601
        /* Perform PSK-to-MS expansion in a single step. */
1602
        psa_status_t status;
1603
        psa_algorithm_t alg;
1604
        psa_key_id_t psk;
1605
        psa_key_derivation_operation_t derivation =
1606
            PSA_KEY_DERIVATION_OPERATION_INIT;
1607
        mbedtls_md_type_t hash_alg = handshake->ciphersuite_info->mac;
1608
1609
        MBEDTLS_SSL_DEBUG_MSG(2, ("perform PSA-based PSK-to-MS expansion"));
1610
1611
        psk = mbedtls_ssl_get_opaque_psk(ssl);
1612
1613
        if (hash_alg == MBEDTLS_MD_SHA384) {
1614
            alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_384);
1615
        } else {
1616
            alg = PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256);
1617
        }
1618
1619
        status = setup_psa_key_derivation(&derivation, psk, alg,
1620
                                          salt, salt_len,
1621
                                          (unsigned char const *) lbl,
1622
                                          (size_t) strlen(lbl),
1623
                                          master_secret_len);
1624
        if (status != PSA_SUCCESS) {
1625
            psa_key_derivation_abort(&derivation);
1626
            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
1627
        }
1628
1629
        status = psa_key_derivation_output_bytes(&derivation,
1630
                                                 master,
1631
                                                 master_secret_len);
1632
        if (status != PSA_SUCCESS) {
1633
            psa_key_derivation_abort(&derivation);
1634
            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
1635
        }
1636
1637
        status = psa_key_derivation_abort(&derivation);
1638
        if (status != PSA_SUCCESS) {
1639
            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
1640
        }
1641
    } else
1642
#endif
1643
0
    {
1644
0
        ret = handshake->tls_prf(handshake->premaster, handshake->pmslen,
1645
0
                                 lbl, salt, salt_len,
1646
0
                                 master,
1647
0
                                 master_secret_len);
1648
0
        if (ret != 0) {
1649
0
            MBEDTLS_SSL_DEBUG_RET(1, "prf", ret);
1650
0
            return ret;
1651
0
        }
1652
1653
0
        MBEDTLS_SSL_DEBUG_BUF(3, "premaster secret",
1654
0
                              handshake->premaster,
1655
0
                              handshake->pmslen);
1656
1657
0
        mbedtls_platform_zeroize(handshake->premaster,
1658
0
                                 sizeof(handshake->premaster));
1659
0
    }
1660
1661
0
    return 0;
1662
0
}
1663
1664
int mbedtls_ssl_derive_keys(mbedtls_ssl_context *ssl)
1665
0
{
1666
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1667
0
    const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
1668
0
        ssl->handshake->ciphersuite_info;
1669
1670
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> derive keys"));
1671
1672
    /* Set PRF, calc_verify and calc_finished function pointers */
1673
0
    ret = ssl_set_handshake_prfs(ssl->handshake,
1674
0
                                 ssl->minor_ver,
1675
0
                                 ciphersuite_info->mac);
1676
0
    if (ret != 0) {
1677
0
        MBEDTLS_SSL_DEBUG_RET(1, "ssl_set_handshake_prfs", ret);
1678
0
        return ret;
1679
0
    }
1680
1681
    /* Compute master secret if needed */
1682
0
    ret = ssl_compute_master(ssl->handshake,
1683
0
                             ssl->session_negotiate->master,
1684
0
                             ssl);
1685
0
    if (ret != 0) {
1686
0
        MBEDTLS_SSL_DEBUG_RET(1, "ssl_compute_master", ret);
1687
0
        return ret;
1688
0
    }
1689
1690
    /* Swap the client and server random values:
1691
     * - MS derivation wanted client+server (RFC 5246 8.1)
1692
     * - key derivation wants server+client (RFC 5246 6.3) */
1693
0
    {
1694
0
        unsigned char tmp[64];
1695
0
        memcpy(tmp, ssl->handshake->randbytes, 64);
1696
0
        memcpy(ssl->handshake->randbytes, tmp + 32, 32);
1697
0
        memcpy(ssl->handshake->randbytes + 32, tmp, 32);
1698
0
        mbedtls_platform_zeroize(tmp, sizeof(tmp));
1699
0
    }
1700
1701
    /* Populate transform structure */
1702
0
    ret = ssl_populate_transform(ssl->transform_negotiate,
1703
0
                                 ssl->session_negotiate->ciphersuite,
1704
0
                                 ssl->session_negotiate->master,
1705
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
1706
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
1707
                                 ssl->session_negotiate->encrypt_then_mac,
1708
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
1709
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
1710
                                 ssl->session_negotiate->trunc_hmac,
1711
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
1712
#endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
1713
#if defined(MBEDTLS_ZLIB_SUPPORT)
1714
                                 ssl->session_negotiate->compression,
1715
#endif
1716
0
                                 ssl->handshake->tls_prf,
1717
0
                                 ssl->handshake->randbytes,
1718
0
                                 ssl->minor_ver,
1719
0
                                 ssl->conf->endpoint,
1720
0
                                 ssl);
1721
0
    if (ret != 0) {
1722
0
        MBEDTLS_SSL_DEBUG_RET(1, "ssl_populate_transform", ret);
1723
0
        return ret;
1724
0
    }
1725
1726
    /* We no longer need Server/ClientHello.random values */
1727
0
    mbedtls_platform_zeroize(ssl->handshake->randbytes,
1728
0
                             sizeof(ssl->handshake->randbytes));
1729
1730
    /* Allocate compression buffer */
1731
#if defined(MBEDTLS_ZLIB_SUPPORT)
1732
    if (ssl->session_negotiate->compression == MBEDTLS_SSL_COMPRESS_DEFLATE &&
1733
        ssl->compress_buf == NULL) {
1734
        MBEDTLS_SSL_DEBUG_MSG(3, ("Allocating compression buffer"));
1735
        ssl->compress_buf = mbedtls_calloc(1, MBEDTLS_SSL_COMPRESS_BUFFER_LEN);
1736
        if (ssl->compress_buf == NULL) {
1737
            MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%d bytes) failed",
1738
                                      MBEDTLS_SSL_COMPRESS_BUFFER_LEN));
1739
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
1740
        }
1741
    }
1742
#endif
1743
1744
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= derive keys"));
1745
1746
0
    return 0;
1747
0
}
1748
1749
#if defined(MBEDTLS_SSL_PROTO_SSL3)
1750
void ssl_calc_verify_ssl(const mbedtls_ssl_context *ssl,
1751
                         unsigned char *hash,
1752
                         size_t *hlen)
1753
{
1754
    mbedtls_md5_context md5;
1755
    mbedtls_sha1_context sha1;
1756
    unsigned char pad_1[48];
1757
    unsigned char pad_2[48];
1758
1759
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify ssl"));
1760
1761
    mbedtls_md5_init(&md5);
1762
    mbedtls_sha1_init(&sha1);
1763
1764
    mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
1765
    mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
1766
1767
    memset(pad_1, 0x36, 48);
1768
    memset(pad_2, 0x5C, 48);
1769
1770
    mbedtls_md5_update_ret(&md5, ssl->session_negotiate->master, 48);
1771
    mbedtls_md5_update_ret(&md5, pad_1, 48);
1772
    mbedtls_md5_finish_ret(&md5, hash);
1773
1774
    mbedtls_md5_starts_ret(&md5);
1775
    mbedtls_md5_update_ret(&md5, ssl->session_negotiate->master, 48);
1776
    mbedtls_md5_update_ret(&md5, pad_2, 48);
1777
    mbedtls_md5_update_ret(&md5, hash,  16);
1778
    mbedtls_md5_finish_ret(&md5, hash);
1779
1780
    mbedtls_sha1_update_ret(&sha1, ssl->session_negotiate->master, 48);
1781
    mbedtls_sha1_update_ret(&sha1, pad_1, 40);
1782
    mbedtls_sha1_finish_ret(&sha1, hash + 16);
1783
1784
    mbedtls_sha1_starts_ret(&sha1);
1785
    mbedtls_sha1_update_ret(&sha1, ssl->session_negotiate->master, 48);
1786
    mbedtls_sha1_update_ret(&sha1, pad_2, 40);
1787
    mbedtls_sha1_update_ret(&sha1, hash + 16, 20);
1788
    mbedtls_sha1_finish_ret(&sha1, hash + 16);
1789
1790
    *hlen = 36;
1791
1792
    MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1793
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1794
1795
    mbedtls_md5_free(&md5);
1796
    mbedtls_sha1_free(&sha1);
1797
1798
    return;
1799
}
1800
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
1801
1802
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
1803
void ssl_calc_verify_tls(const mbedtls_ssl_context *ssl,
1804
                         unsigned char *hash,
1805
                         size_t *hlen)
1806
{
1807
    mbedtls_md5_context md5;
1808
    mbedtls_sha1_context sha1;
1809
1810
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify tls"));
1811
1812
    mbedtls_md5_init(&md5);
1813
    mbedtls_sha1_init(&sha1);
1814
1815
    mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
1816
    mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
1817
1818
    mbedtls_md5_finish_ret(&md5,  hash);
1819
    mbedtls_sha1_finish_ret(&sha1, hash + 16);
1820
1821
    *hlen = 36;
1822
1823
    MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1824
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1825
1826
    mbedtls_md5_free(&md5);
1827
    mbedtls_sha1_free(&sha1);
1828
1829
    return;
1830
}
1831
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
1832
1833
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
1834
#if defined(MBEDTLS_SHA256_C)
1835
void ssl_calc_verify_tls_sha256(const mbedtls_ssl_context *ssl,
1836
                                unsigned char *hash,
1837
                                size_t *hlen)
1838
0
{
1839
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1840
    size_t hash_size;
1841
    psa_status_t status;
1842
    psa_hash_operation_t sha256_psa = psa_hash_operation_init();
1843
1844
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> PSA calc verify sha256"));
1845
    status = psa_hash_clone(&ssl->handshake->fin_sha256_psa, &sha256_psa);
1846
    if (status != PSA_SUCCESS) {
1847
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
1848
        return;
1849
    }
1850
1851
    status = psa_hash_finish(&sha256_psa, hash, 32, &hash_size);
1852
    if (status != PSA_SUCCESS) {
1853
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
1854
        return;
1855
    }
1856
1857
    *hlen = 32;
1858
    MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated verify result", hash, *hlen);
1859
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= PSA calc verify"));
1860
#else
1861
0
    mbedtls_sha256_context sha256;
1862
1863
0
    mbedtls_sha256_init(&sha256);
1864
1865
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify sha256"));
1866
1867
0
    mbedtls_sha256_clone(&sha256, &ssl->handshake->fin_sha256);
1868
0
    mbedtls_sha256_finish_ret(&sha256, hash);
1869
1870
0
    *hlen = 32;
1871
1872
0
    MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1873
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1874
1875
0
    mbedtls_sha256_free(&sha256);
1876
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1877
0
    return;
1878
0
}
1879
#endif /* MBEDTLS_SHA256_C */
1880
1881
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
1882
void ssl_calc_verify_tls_sha384(const mbedtls_ssl_context *ssl,
1883
                                unsigned char *hash,
1884
                                size_t *hlen)
1885
{
1886
#if defined(MBEDTLS_USE_PSA_CRYPTO)
1887
    size_t hash_size;
1888
    psa_status_t status;
1889
    psa_hash_operation_t sha384_psa = psa_hash_operation_init();
1890
1891
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> PSA calc verify sha384"));
1892
    status = psa_hash_clone(&ssl->handshake->fin_sha384_psa, &sha384_psa);
1893
    if (status != PSA_SUCCESS) {
1894
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
1895
        return;
1896
    }
1897
1898
    status = psa_hash_finish(&sha384_psa, hash, 48, &hash_size);
1899
    if (status != PSA_SUCCESS) {
1900
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
1901
        return;
1902
    }
1903
1904
    *hlen = 48;
1905
    MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated verify result", hash, *hlen);
1906
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= PSA calc verify"));
1907
#else
1908
    mbedtls_sha512_context sha512;
1909
1910
    mbedtls_sha512_init(&sha512);
1911
1912
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc verify sha384"));
1913
1914
    mbedtls_sha512_clone(&sha512, &ssl->handshake->fin_sha512);
1915
    mbedtls_sha512_finish_ret(&sha512, hash);
1916
1917
    *hlen = 48;
1918
1919
    MBEDTLS_SSL_DEBUG_BUF(3, "calculated verify result", hash, *hlen);
1920
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc verify"));
1921
1922
    mbedtls_sha512_free(&sha512);
1923
#endif /* MBEDTLS_USE_PSA_CRYPTO */
1924
    return;
1925
}
1926
#endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
1927
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
1928
1929
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
1930
int mbedtls_ssl_psk_derive_premaster(mbedtls_ssl_context *ssl, mbedtls_key_exchange_type_t key_ex)
1931
0
{
1932
0
    unsigned char *p = ssl->handshake->premaster;
1933
0
    unsigned char *end = p + sizeof(ssl->handshake->premaster);
1934
0
    const unsigned char *psk = NULL;
1935
0
    size_t psk_len = 0;
1936
1937
0
    if (mbedtls_ssl_get_psk(ssl, &psk, &psk_len)
1938
0
        == MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED) {
1939
        /*
1940
         * This should never happen because the existence of a PSK is always
1941
         * checked before calling this function
1942
         */
1943
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
1944
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
1945
0
    }
1946
1947
    /*
1948
     * PMS = struct {
1949
     *     opaque other_secret<0..2^16-1>;
1950
     *     opaque psk<0..2^16-1>;
1951
     * };
1952
     * with "other_secret" depending on the particular key exchange
1953
     */
1954
0
#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
1955
0
    if (key_ex == MBEDTLS_KEY_EXCHANGE_PSK) {
1956
0
        if (end - p < 2) {
1957
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1958
0
        }
1959
1960
0
        MBEDTLS_PUT_UINT16_BE(psk_len, p, 0);
1961
0
        p += 2;
1962
1963
0
        if (end < p || (size_t) (end - p) < psk_len) {
1964
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1965
0
        }
1966
1967
0
        memset(p, 0, psk_len);
1968
0
        p += psk_len;
1969
0
    } else
1970
0
#endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */
1971
#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
1972
    if (key_ex == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
1973
        /*
1974
         * other_secret already set by the ClientKeyExchange message,
1975
         * and is 48 bytes long
1976
         */
1977
        if (end - p < 2) {
1978
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
1979
        }
1980
1981
        *p++ = 0;
1982
        *p++ = 48;
1983
        p += 48;
1984
    } else
1985
#endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */
1986
#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
1987
    if (key_ex == MBEDTLS_KEY_EXCHANGE_DHE_PSK) {
1988
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1989
        size_t len;
1990
1991
        /* Write length only when we know the actual value */
1992
        if ((ret = mbedtls_dhm_calc_secret(&ssl->handshake->dhm_ctx,
1993
                                           p + 2, end - (p + 2), &len,
1994
                                           ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
1995
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_dhm_calc_secret", ret);
1996
            return ret;
1997
        }
1998
        MBEDTLS_PUT_UINT16_BE(len, p, 0);
1999
        p += 2 + len;
2000
2001
        MBEDTLS_SSL_DEBUG_MPI(3, "DHM: K ", &ssl->handshake->dhm_ctx.K);
2002
    } else
2003
#endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */
2004
#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
2005
    if (key_ex == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK) {
2006
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2007
        size_t zlen;
2008
2009
        if ((ret = mbedtls_ecdh_calc_secret(&ssl->handshake->ecdh_ctx, &zlen,
2010
                                            p + 2, end - (p + 2),
2011
                                            ssl->conf->f_rng, ssl->conf->p_rng)) != 0) {
2012
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ecdh_calc_secret", ret);
2013
            return ret;
2014
        }
2015
2016
        MBEDTLS_PUT_UINT16_BE(zlen, p, 0);
2017
        p += 2 + zlen;
2018
2019
        MBEDTLS_SSL_DEBUG_ECDH(3, &ssl->handshake->ecdh_ctx,
2020
                               MBEDTLS_DEBUG_ECDH_Z);
2021
    } else
2022
#endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */
2023
0
    {
2024
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2025
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2026
0
    }
2027
2028
    /* opaque psk<0..2^16-1>; */
2029
0
    if (end - p < 2) {
2030
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2031
0
    }
2032
2033
0
    MBEDTLS_PUT_UINT16_BE(psk_len, p, 0);
2034
0
    p += 2;
2035
2036
0
    if (end < p || (size_t) (end - p) < psk_len) {
2037
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
2038
0
    }
2039
2040
0
    memcpy(p, psk, psk_len);
2041
0
    p += psk_len;
2042
2043
0
    ssl->handshake->pmslen = p - ssl->handshake->premaster;
2044
2045
0
    return 0;
2046
0
}
2047
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
2048
2049
#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_RENEGOTIATION)
2050
MBEDTLS_CHECK_RETURN_CRITICAL
2051
static int ssl_write_hello_request(mbedtls_ssl_context *ssl);
2052
2053
#if defined(MBEDTLS_SSL_PROTO_DTLS)
2054
int mbedtls_ssl_resend_hello_request(mbedtls_ssl_context *ssl)
2055
{
2056
    /* If renegotiation is not enforced, retransmit until we would reach max
2057
     * timeout if we were using the usual handshake doubling scheme */
2058
    if (ssl->conf->renego_max_records < 0) {
2059
        uint32_t ratio = ssl->conf->hs_timeout_max / ssl->conf->hs_timeout_min + 1;
2060
        unsigned char doublings = 1;
2061
2062
        while (ratio != 0) {
2063
            ++doublings;
2064
            ratio >>= 1;
2065
        }
2066
2067
        if (++ssl->renego_records_seen > doublings) {
2068
            MBEDTLS_SSL_DEBUG_MSG(2, ("no longer retransmitting hello request"));
2069
            return 0;
2070
        }
2071
    }
2072
2073
    return ssl_write_hello_request(ssl);
2074
}
2075
#endif
2076
#endif /* MBEDTLS_SSL_SRV_C && MBEDTLS_SSL_RENEGOTIATION */
2077
2078
#if defined(MBEDTLS_X509_CRT_PARSE_C)
2079
static void ssl_clear_peer_cert(mbedtls_ssl_session *session)
2080
4.38k
{
2081
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2082
    if (session->peer_cert != NULL) {
2083
        mbedtls_x509_crt_free(session->peer_cert);
2084
        mbedtls_free(session->peer_cert);
2085
        session->peer_cert = NULL;
2086
    }
2087
#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2088
4.38k
    if (session->peer_cert_digest != NULL) {
2089
        /* Zeroization is not necessary. */
2090
0
        mbedtls_free(session->peer_cert_digest);
2091
0
        session->peer_cert_digest      = NULL;
2092
0
        session->peer_cert_digest_type = MBEDTLS_MD_NONE;
2093
0
        session->peer_cert_digest_len  = 0;
2094
0
    }
2095
4.38k
#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2096
4.38k
}
2097
#endif /* MBEDTLS_X509_CRT_PARSE_C */
2098
2099
/*
2100
 * Handshake functions
2101
 */
2102
#if !defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
2103
/* No certificate support -> dummy functions */
2104
int mbedtls_ssl_write_certificate(mbedtls_ssl_context *ssl)
2105
{
2106
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2107
        ssl->handshake->ciphersuite_info;
2108
2109
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate"));
2110
2111
    if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2112
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate"));
2113
        ssl->state++;
2114
        return 0;
2115
    }
2116
2117
    MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2118
    return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2119
}
2120
2121
int mbedtls_ssl_parse_certificate(mbedtls_ssl_context *ssl)
2122
{
2123
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2124
        ssl->handshake->ciphersuite_info;
2125
2126
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate"));
2127
2128
    if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2129
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate"));
2130
        ssl->state++;
2131
        return 0;
2132
    }
2133
2134
    MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2135
    return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2136
}
2137
2138
#else /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2139
/* Some certificate support -> implement write and parse */
2140
2141
int mbedtls_ssl_write_certificate(mbedtls_ssl_context *ssl)
2142
0
{
2143
0
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
2144
0
    size_t i, n;
2145
0
    const mbedtls_x509_crt *crt;
2146
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2147
0
        ssl->handshake->ciphersuite_info;
2148
2149
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write certificate"));
2150
2151
0
    if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2152
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate"));
2153
0
        ssl->state++;
2154
0
        return 0;
2155
0
    }
2156
2157
0
#if defined(MBEDTLS_SSL_CLI_C)
2158
0
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
2159
0
        if (ssl->client_auth == 0) {
2160
0
            MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip write certificate"));
2161
0
            ssl->state++;
2162
0
            return 0;
2163
0
        }
2164
2165
#if defined(MBEDTLS_SSL_PROTO_SSL3)
2166
        /*
2167
         * If using SSLv3 and got no cert, send an Alert message
2168
         * (otherwise an empty Certificate message will be sent).
2169
         */
2170
        if (mbedtls_ssl_own_cert(ssl)  == NULL &&
2171
            ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
2172
            ssl->out_msglen  = 2;
2173
            ssl->out_msgtype = MBEDTLS_SSL_MSG_ALERT;
2174
            ssl->out_msg[0]  = MBEDTLS_SSL_ALERT_LEVEL_WARNING;
2175
            ssl->out_msg[1]  = MBEDTLS_SSL_ALERT_MSG_NO_CERT;
2176
2177
            MBEDTLS_SSL_DEBUG_MSG(2, ("got no certificate to send"));
2178
            goto write_msg;
2179
        }
2180
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
2181
0
    }
2182
0
#endif /* MBEDTLS_SSL_CLI_C */
2183
0
#if defined(MBEDTLS_SSL_SRV_C)
2184
0
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
2185
0
        if (mbedtls_ssl_own_cert(ssl) == NULL) {
2186
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("got no certificate to send"));
2187
0
            return MBEDTLS_ERR_SSL_CERTIFICATE_REQUIRED;
2188
0
        }
2189
0
    }
2190
0
#endif
2191
2192
0
    MBEDTLS_SSL_DEBUG_CRT(3, "own certificate", mbedtls_ssl_own_cert(ssl));
2193
2194
    /*
2195
     *     0  .  0    handshake type
2196
     *     1  .  3    handshake length
2197
     *     4  .  6    length of all certs
2198
     *     7  .  9    length of cert. 1
2199
     *    10  . n-1   peer certificate
2200
     *     n  . n+2   length of cert. 2
2201
     *    n+3 . ...   upper level cert, etc.
2202
     */
2203
0
    i = 7;
2204
0
    crt = mbedtls_ssl_own_cert(ssl);
2205
2206
0
    while (crt != NULL) {
2207
0
        n = crt->raw.len;
2208
0
        if (n > MBEDTLS_SSL_OUT_CONTENT_LEN - 3 - i) {
2209
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("certificate too large, %" MBEDTLS_PRINTF_SIZET
2210
0
                                      " > %" MBEDTLS_PRINTF_SIZET,
2211
0
                                      i + 3 + n, (size_t) MBEDTLS_SSL_OUT_CONTENT_LEN));
2212
0
            return MBEDTLS_ERR_SSL_CERTIFICATE_TOO_LARGE;
2213
0
        }
2214
2215
0
        ssl->out_msg[i] = MBEDTLS_BYTE_2(n);
2216
0
        ssl->out_msg[i + 1] = MBEDTLS_BYTE_1(n);
2217
0
        ssl->out_msg[i + 2] = MBEDTLS_BYTE_0(n);
2218
2219
0
        i += 3; memcpy(ssl->out_msg + i, crt->raw.p, n);
2220
0
        i += n; crt = crt->next;
2221
0
    }
2222
2223
0
    ssl->out_msg[4]  = MBEDTLS_BYTE_2(i - 7);
2224
0
    ssl->out_msg[5]  = MBEDTLS_BYTE_1(i - 7);
2225
0
    ssl->out_msg[6]  = MBEDTLS_BYTE_0(i - 7);
2226
2227
0
    ssl->out_msglen  = i;
2228
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
2229
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_CERTIFICATE;
2230
2231
#if defined(MBEDTLS_SSL_PROTO_SSL3) && defined(MBEDTLS_SSL_CLI_C)
2232
write_msg:
2233
#endif
2234
2235
0
    ssl->state++;
2236
2237
0
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
2238
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
2239
0
        return ret;
2240
0
    }
2241
2242
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write certificate"));
2243
2244
0
    return ret;
2245
0
}
2246
2247
#if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2248
2249
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2250
MBEDTLS_CHECK_RETURN_CRITICAL
2251
static int ssl_check_peer_crt_unchanged(mbedtls_ssl_context *ssl,
2252
                                        unsigned char *crt_buf,
2253
                                        size_t crt_buf_len)
2254
{
2255
    mbedtls_x509_crt const * const peer_crt = ssl->session->peer_cert;
2256
2257
    if (peer_crt == NULL) {
2258
        return -1;
2259
    }
2260
2261
    if (peer_crt->raw.len != crt_buf_len) {
2262
        return -1;
2263
    }
2264
2265
    return memcmp(peer_crt->raw.p, crt_buf, peer_crt->raw.len);
2266
}
2267
#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2268
MBEDTLS_CHECK_RETURN_CRITICAL
2269
static int ssl_check_peer_crt_unchanged(mbedtls_ssl_context *ssl,
2270
                                        unsigned char *crt_buf,
2271
                                        size_t crt_buf_len)
2272
{
2273
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2274
    unsigned char const * const peer_cert_digest =
2275
        ssl->session->peer_cert_digest;
2276
    mbedtls_md_type_t const peer_cert_digest_type =
2277
        ssl->session->peer_cert_digest_type;
2278
    mbedtls_md_info_t const * const digest_info =
2279
        mbedtls_md_info_from_type(peer_cert_digest_type);
2280
    unsigned char tmp_digest[MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN];
2281
    size_t digest_len;
2282
2283
    if (peer_cert_digest == NULL || digest_info == NULL) {
2284
        return -1;
2285
    }
2286
2287
    digest_len = mbedtls_md_get_size(digest_info);
2288
    if (digest_len > MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN) {
2289
        return -1;
2290
    }
2291
2292
    ret = mbedtls_md(digest_info, crt_buf, crt_buf_len, tmp_digest);
2293
    if (ret != 0) {
2294
        return -1;
2295
    }
2296
2297
    return memcmp(tmp_digest, peer_cert_digest, digest_len);
2298
}
2299
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2300
#endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
2301
2302
/*
2303
 * Once the certificate message is read, parse it into a cert chain and
2304
 * perform basic checks, but leave actual verification to the caller
2305
 */
2306
MBEDTLS_CHECK_RETURN_CRITICAL
2307
static int ssl_parse_certificate_chain(mbedtls_ssl_context *ssl,
2308
                                       mbedtls_x509_crt *chain)
2309
0
{
2310
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2311
#if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2312
    int crt_cnt = 0;
2313
#endif
2314
0
    size_t i, n;
2315
0
    uint8_t alert;
2316
2317
0
    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
2318
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2319
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2320
0
                                       MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
2321
0
        return MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
2322
0
    }
2323
2324
0
    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE ||
2325
0
        ssl->in_hslen < mbedtls_ssl_hs_hdr_len(ssl) + 3 + 3) {
2326
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2327
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2328
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2329
0
        return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2330
0
    }
2331
2332
0
    i = mbedtls_ssl_hs_hdr_len(ssl);
2333
2334
    /*
2335
     * Same message structure as in mbedtls_ssl_write_certificate()
2336
     */
2337
0
    n = (ssl->in_msg[i+1] << 8) | ssl->in_msg[i+2];
2338
2339
0
    if (ssl->in_msg[i] != 0 ||
2340
0
        ssl->in_hslen != n + 3 + mbedtls_ssl_hs_hdr_len(ssl)) {
2341
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2342
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2343
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2344
0
        return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2345
0
    }
2346
2347
    /* Make &ssl->in_msg[i] point to the beginning of the CRT chain. */
2348
0
    i += 3;
2349
2350
    /* Iterate through and parse the CRTs in the provided chain. */
2351
0
    while (i < ssl->in_hslen) {
2352
        /* Check that there's room for the next CRT's length fields. */
2353
0
        if (i + 3 > ssl->in_hslen) {
2354
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2355
0
            mbedtls_ssl_send_alert_message(ssl,
2356
0
                                           MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2357
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2358
0
            return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2359
0
        }
2360
        /* In theory, the CRT can be up to 2**24 Bytes, but we don't support
2361
         * anything beyond 2**16 ~ 64K. */
2362
0
        if (ssl->in_msg[i] != 0) {
2363
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2364
0
            mbedtls_ssl_send_alert_message(ssl,
2365
0
                                           MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2366
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2367
0
            return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2368
0
        }
2369
2370
        /* Read length of the next CRT in the chain. */
2371
0
        n = ((unsigned int) ssl->in_msg[i + 1] << 8)
2372
0
            | (unsigned int) ssl->in_msg[i + 2];
2373
0
        i += 3;
2374
2375
0
        if (n < 128 || i + n > ssl->in_hslen) {
2376
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate message"));
2377
0
            mbedtls_ssl_send_alert_message(ssl,
2378
0
                                           MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2379
0
                                           MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
2380
0
            return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2381
0
        }
2382
2383
        /* Check if we're handling the first CRT in the chain. */
2384
#if defined(MBEDTLS_SSL_RENEGOTIATION) && defined(MBEDTLS_SSL_CLI_C)
2385
        if (crt_cnt++ == 0 &&
2386
            ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
2387
            ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
2388
            /* During client-side renegotiation, check that the server's
2389
             * end-CRTs hasn't changed compared to the initial handshake,
2390
             * mitigating the triple handshake attack. On success, reuse
2391
             * the original end-CRT instead of parsing it again. */
2392
            MBEDTLS_SSL_DEBUG_MSG(3, ("Check that peer CRT hasn't changed during renegotiation"));
2393
            if (ssl_check_peer_crt_unchanged(ssl,
2394
                                             &ssl->in_msg[i],
2395
                                             n) != 0) {
2396
                MBEDTLS_SSL_DEBUG_MSG(1, ("new server cert during renegotiation"));
2397
                mbedtls_ssl_send_alert_message(ssl,
2398
                                               MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2399
                                               MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED);
2400
                return MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2401
            }
2402
2403
            /* Now we can safely free the original chain. */
2404
            ssl_clear_peer_cert(ssl->session);
2405
        }
2406
#endif /* MBEDTLS_SSL_RENEGOTIATION && MBEDTLS_SSL_CLI_C */
2407
2408
        /* Parse the next certificate in the chain. */
2409
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2410
        ret = mbedtls_x509_crt_parse_der(chain, ssl->in_msg + i, n);
2411
#else
2412
        /* If we don't need to store the CRT chain permanently, parse
2413
         * it in-place from the input buffer instead of making a copy. */
2414
0
        ret = mbedtls_x509_crt_parse_der_nocopy(chain, ssl->in_msg + i, n);
2415
0
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2416
0
        switch (ret) {
2417
0
            case 0: /*ok*/
2418
0
            case MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG + MBEDTLS_ERR_OID_NOT_FOUND:
2419
                /* Ignore certificate with an unknown algorithm: maybe a
2420
                   prior certificate was already trusted. */
2421
0
                break;
2422
2423
0
            case MBEDTLS_ERR_X509_ALLOC_FAILED:
2424
0
                alert = MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR;
2425
0
                goto crt_parse_der_failed;
2426
2427
0
            case MBEDTLS_ERR_X509_UNKNOWN_VERSION:
2428
0
                alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2429
0
                goto crt_parse_der_failed;
2430
2431
0
            default:
2432
0
                alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
2433
0
crt_parse_der_failed:
2434
0
                mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, alert);
2435
0
                MBEDTLS_SSL_DEBUG_RET(1, " mbedtls_x509_crt_parse_der", ret);
2436
0
                return ret;
2437
0
        }
2438
2439
0
        i += n;
2440
0
    }
2441
2442
0
    MBEDTLS_SSL_DEBUG_CRT(3, "peer certificate", chain);
2443
0
    return 0;
2444
0
}
2445
2446
#if defined(MBEDTLS_SSL_SRV_C)
2447
MBEDTLS_CHECK_RETURN_CRITICAL
2448
static int ssl_srv_check_client_no_crt_notification(mbedtls_ssl_context *ssl)
2449
0
{
2450
0
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
2451
0
        return -1;
2452
0
    }
2453
2454
#if defined(MBEDTLS_SSL_PROTO_SSL3)
2455
    /*
2456
     * Check if the client sent an empty certificate
2457
     */
2458
    if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
2459
        if (ssl->in_msglen  == 2                        &&
2460
            ssl->in_msgtype == MBEDTLS_SSL_MSG_ALERT            &&
2461
            ssl->in_msg[0]  == MBEDTLS_SSL_ALERT_LEVEL_WARNING  &&
2462
            ssl->in_msg[1]  == MBEDTLS_SSL_ALERT_MSG_NO_CERT) {
2463
            MBEDTLS_SSL_DEBUG_MSG(1, ("SSLv3 client has no certificate"));
2464
            return 0;
2465
        }
2466
2467
        return -1;
2468
    }
2469
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
2470
2471
0
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
2472
0
    defined(MBEDTLS_SSL_PROTO_TLS1_2)
2473
0
    if (ssl->in_hslen   == 3 + mbedtls_ssl_hs_hdr_len(ssl) &&
2474
0
        ssl->in_msgtype == MBEDTLS_SSL_MSG_HANDSHAKE    &&
2475
0
        ssl->in_msg[0]  == MBEDTLS_SSL_HS_CERTIFICATE   &&
2476
0
        memcmp(ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl), "\0\0\0", 3) == 0) {
2477
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("TLSv1 client has no certificate"));
2478
0
        return 0;
2479
0
    }
2480
2481
0
    return -1;
2482
0
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
2483
          MBEDTLS_SSL_PROTO_TLS1_2 */
2484
0
}
2485
#endif /* MBEDTLS_SSL_SRV_C */
2486
2487
/* Check if a certificate message is expected.
2488
 * Return either
2489
 * - SSL_CERTIFICATE_EXPECTED, or
2490
 * - SSL_CERTIFICATE_SKIP
2491
 * indicating whether a Certificate message is expected or not.
2492
 */
2493
0
#define SSL_CERTIFICATE_EXPECTED 0
2494
0
#define SSL_CERTIFICATE_SKIP     1
2495
MBEDTLS_CHECK_RETURN_CRITICAL
2496
static int ssl_parse_certificate_coordinate(mbedtls_ssl_context *ssl,
2497
                                            int authmode)
2498
0
{
2499
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2500
0
        ssl->handshake->ciphersuite_info;
2501
2502
0
    if (!mbedtls_ssl_ciphersuite_uses_srv_cert(ciphersuite_info)) {
2503
0
        return SSL_CERTIFICATE_SKIP;
2504
0
    }
2505
2506
0
#if defined(MBEDTLS_SSL_SRV_C)
2507
0
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
2508
0
        if (ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK) {
2509
0
            return SSL_CERTIFICATE_SKIP;
2510
0
        }
2511
2512
0
        if (authmode == MBEDTLS_SSL_VERIFY_NONE) {
2513
0
            ssl->session_negotiate->verify_result =
2514
0
                MBEDTLS_X509_BADCERT_SKIP_VERIFY;
2515
0
            return SSL_CERTIFICATE_SKIP;
2516
0
        }
2517
0
    }
2518
#else
2519
    ((void) authmode);
2520
#endif /* MBEDTLS_SSL_SRV_C */
2521
2522
0
    return SSL_CERTIFICATE_EXPECTED;
2523
0
}
2524
2525
MBEDTLS_CHECK_RETURN_CRITICAL
2526
static int ssl_parse_certificate_verify(mbedtls_ssl_context *ssl,
2527
                                        int authmode,
2528
                                        mbedtls_x509_crt *chain,
2529
                                        void *rs_ctx)
2530
0
{
2531
0
    int ret = 0;
2532
0
    const mbedtls_ssl_ciphersuite_t *ciphersuite_info =
2533
0
        ssl->handshake->ciphersuite_info;
2534
0
    int have_ca_chain = 0;
2535
2536
0
    int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *);
2537
0
    void *p_vrfy;
2538
2539
0
    if (authmode == MBEDTLS_SSL_VERIFY_NONE) {
2540
0
        return 0;
2541
0
    }
2542
2543
0
    if (ssl->f_vrfy != NULL) {
2544
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("Use context-specific verification callback"));
2545
0
        f_vrfy = ssl->f_vrfy;
2546
0
        p_vrfy = ssl->p_vrfy;
2547
0
    } else {
2548
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("Use configuration-specific verification callback"));
2549
0
        f_vrfy = ssl->conf->f_vrfy;
2550
0
        p_vrfy = ssl->conf->p_vrfy;
2551
0
    }
2552
2553
    /*
2554
     * Main check: verify certificate
2555
     */
2556
#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
2557
    if (ssl->conf->f_ca_cb != NULL) {
2558
        ((void) rs_ctx);
2559
        have_ca_chain = 1;
2560
2561
        MBEDTLS_SSL_DEBUG_MSG(3, ("use CA callback for X.509 CRT verification"));
2562
        ret = mbedtls_x509_crt_verify_with_ca_cb(
2563
            chain,
2564
            ssl->conf->f_ca_cb,
2565
            ssl->conf->p_ca_cb,
2566
            ssl->conf->cert_profile,
2567
            ssl->hostname,
2568
            &ssl->session_negotiate->verify_result,
2569
            f_vrfy, p_vrfy);
2570
    } else
2571
#endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
2572
0
    {
2573
0
        mbedtls_x509_crt *ca_chain;
2574
0
        mbedtls_x509_crl *ca_crl;
2575
2576
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2577
        if (ssl->handshake->sni_ca_chain != NULL) {
2578
            ca_chain = ssl->handshake->sni_ca_chain;
2579
            ca_crl   = ssl->handshake->sni_ca_crl;
2580
        } else
2581
#endif
2582
0
        {
2583
0
            ca_chain = ssl->conf->ca_chain;
2584
0
            ca_crl   = ssl->conf->ca_crl;
2585
0
        }
2586
2587
0
        if (ca_chain != NULL) {
2588
0
            have_ca_chain = 1;
2589
0
        }
2590
2591
0
        ret = mbedtls_x509_crt_verify_restartable(
2592
0
            chain,
2593
0
            ca_chain, ca_crl,
2594
0
            ssl->conf->cert_profile,
2595
0
            ssl->hostname,
2596
0
            &ssl->session_negotiate->verify_result,
2597
0
            f_vrfy, p_vrfy, rs_ctx);
2598
0
    }
2599
2600
0
    if (ret != 0) {
2601
0
        MBEDTLS_SSL_DEBUG_RET(1, "x509_verify_cert", ret);
2602
0
    }
2603
2604
#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2605
    if (ret == MBEDTLS_ERR_ECP_IN_PROGRESS) {
2606
        return MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS;
2607
    }
2608
#endif
2609
2610
    /*
2611
     * Secondary checks: always done, but change 'ret' only if it was 0
2612
     */
2613
2614
0
#if defined(MBEDTLS_ECP_C)
2615
0
    {
2616
0
        const mbedtls_pk_context *pk = &chain->pk;
2617
2618
        /* If certificate uses an EC key, make sure the curve is OK.
2619
         * This is a public key, so it can't be opaque, so can_do() is a good
2620
         * enough check to ensure pk_ec() is safe to use here. */
2621
0
        if (mbedtls_pk_can_do(pk, MBEDTLS_PK_ECKEY) &&
2622
0
            mbedtls_ssl_check_curve(ssl, mbedtls_pk_ec(*pk)->grp.id) != 0) {
2623
0
            ssl->session_negotiate->verify_result |= MBEDTLS_X509_BADCERT_BAD_KEY;
2624
2625
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate (EC key curve)"));
2626
0
            if (ret == 0) {
2627
0
                ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2628
0
            }
2629
0
        }
2630
0
    }
2631
0
#endif /* MBEDTLS_ECP_C */
2632
2633
0
    if (mbedtls_ssl_check_cert_usage(chain,
2634
0
                                     ciphersuite_info,
2635
0
                                     !ssl->conf->endpoint,
2636
0
                                     &ssl->session_negotiate->verify_result) != 0) {
2637
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad certificate (usage extensions)"));
2638
0
        if (ret == 0) {
2639
0
            ret = MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE;
2640
0
        }
2641
0
    }
2642
2643
    /* mbedtls_x509_crt_verify_with_profile is supposed to report a
2644
     * verification failure through MBEDTLS_ERR_X509_CERT_VERIFY_FAILED,
2645
     * with details encoded in the verification flags. All other kinds
2646
     * of error codes, including those from the user provided f_vrfy
2647
     * functions, are treated as fatal and lead to a failure of
2648
     * ssl_parse_certificate even if verification was optional. */
2649
0
    if (authmode == MBEDTLS_SSL_VERIFY_OPTIONAL &&
2650
0
        (ret == MBEDTLS_ERR_X509_CERT_VERIFY_FAILED ||
2651
0
         ret == MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE)) {
2652
0
        ret = 0;
2653
0
    }
2654
2655
0
    if (have_ca_chain == 0 && authmode == MBEDTLS_SSL_VERIFY_REQUIRED) {
2656
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("got no CA chain"));
2657
0
        ret = MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED;
2658
0
    }
2659
2660
0
    if (ret != 0) {
2661
0
        uint8_t alert;
2662
2663
        /* The certificate may have been rejected for several reasons.
2664
           Pick one and send the corresponding alert. Which alert to send
2665
           may be a subject of debate in some cases. */
2666
0
        if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_OTHER) {
2667
0
            alert = MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED;
2668
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_CN_MISMATCH) {
2669
0
            alert = MBEDTLS_SSL_ALERT_MSG_BAD_CERT;
2670
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_KEY_USAGE) {
2671
0
            alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2672
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXT_KEY_USAGE) {
2673
0
            alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2674
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NS_CERT_TYPE) {
2675
0
            alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2676
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_PK) {
2677
0
            alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2678
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_BAD_KEY) {
2679
0
            alert = MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT;
2680
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_EXPIRED) {
2681
0
            alert = MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED;
2682
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_REVOKED) {
2683
0
            alert = MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED;
2684
0
        } else if (ssl->session_negotiate->verify_result & MBEDTLS_X509_BADCERT_NOT_TRUSTED) {
2685
0
            alert = MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA;
2686
0
        } else {
2687
0
            alert = MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN;
2688
0
        }
2689
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2690
0
                                       alert);
2691
0
    }
2692
2693
#if defined(MBEDTLS_DEBUG_C)
2694
    if (ssl->session_negotiate->verify_result != 0) {
2695
        MBEDTLS_SSL_DEBUG_MSG(3, ("! Certificate verification flags %08x",
2696
                                  (unsigned int) ssl->session_negotiate->verify_result));
2697
    } else {
2698
        MBEDTLS_SSL_DEBUG_MSG(3, ("Certificate verification flags clear"));
2699
    }
2700
#endif /* MBEDTLS_DEBUG_C */
2701
2702
0
    return ret;
2703
0
}
2704
2705
#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2706
MBEDTLS_CHECK_RETURN_CRITICAL
2707
static int ssl_remember_peer_crt_digest(mbedtls_ssl_context *ssl,
2708
                                        unsigned char *start, size_t len)
2709
0
{
2710
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2711
    /* Remember digest of the peer's end-CRT. */
2712
0
    ssl->session_negotiate->peer_cert_digest =
2713
0
        mbedtls_calloc(1, MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN);
2714
0
    if (ssl->session_negotiate->peer_cert_digest == NULL) {
2715
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%d bytes) failed",
2716
0
                                  MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN));
2717
0
        mbedtls_ssl_send_alert_message(ssl,
2718
0
                                       MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2719
0
                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
2720
2721
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
2722
0
    }
2723
2724
0
    ret = mbedtls_md(mbedtls_md_info_from_type(
2725
0
                         MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE),
2726
0
                     start, len,
2727
0
                     ssl->session_negotiate->peer_cert_digest);
2728
2729
0
    ssl->session_negotiate->peer_cert_digest_type =
2730
0
        MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE;
2731
0
    ssl->session_negotiate->peer_cert_digest_len =
2732
0
        MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN;
2733
2734
0
    return ret;
2735
0
}
2736
2737
MBEDTLS_CHECK_RETURN_CRITICAL
2738
static int ssl_remember_peer_pubkey(mbedtls_ssl_context *ssl,
2739
                                    unsigned char *start, size_t len)
2740
0
{
2741
0
    unsigned char *end = start + len;
2742
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2743
2744
    /* Make a copy of the peer's raw public key. */
2745
0
    mbedtls_pk_init(&ssl->handshake->peer_pubkey);
2746
0
    ret = mbedtls_pk_parse_subpubkey(&start, end,
2747
0
                                     &ssl->handshake->peer_pubkey);
2748
0
    if (ret != 0) {
2749
        /* We should have parsed the public key before. */
2750
0
        return MBEDTLS_ERR_SSL_INTERNAL_ERROR;
2751
0
    }
2752
2753
0
    return 0;
2754
0
}
2755
#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2756
2757
int mbedtls_ssl_parse_certificate(mbedtls_ssl_context *ssl)
2758
0
{
2759
0
    int ret = 0;
2760
0
    int crt_expected;
2761
#if defined(MBEDTLS_SSL_SRV_C) && defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
2762
    const int authmode = ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET
2763
                       ? ssl->handshake->sni_authmode
2764
                       : ssl->conf->authmode;
2765
#else
2766
0
    const int authmode = ssl->conf->authmode;
2767
0
#endif
2768
0
    void *rs_ctx = NULL;
2769
0
    mbedtls_x509_crt *chain = NULL;
2770
2771
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse certificate"));
2772
2773
0
    crt_expected = ssl_parse_certificate_coordinate(ssl, authmode);
2774
0
    if (crt_expected == SSL_CERTIFICATE_SKIP) {
2775
0
        MBEDTLS_SSL_DEBUG_MSG(2, ("<= skip parse certificate"));
2776
0
        goto exit;
2777
0
    }
2778
2779
#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2780
    if (ssl->handshake->ecrs_enabled &&
2781
        ssl->handshake->ecrs_state == ssl_ecrs_crt_verify) {
2782
        chain = ssl->handshake->ecrs_peer_cert;
2783
        ssl->handshake->ecrs_peer_cert = NULL;
2784
        goto crt_verify;
2785
    }
2786
#endif
2787
2788
0
    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
2789
        /* mbedtls_ssl_read_record may have sent an alert already. We
2790
           let it decide whether to alert. */
2791
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
2792
0
        goto exit;
2793
0
    }
2794
2795
0
#if defined(MBEDTLS_SSL_SRV_C)
2796
0
    if (ssl_srv_check_client_no_crt_notification(ssl) == 0) {
2797
0
        ssl->session_negotiate->verify_result = MBEDTLS_X509_BADCERT_MISSING;
2798
2799
0
        if (authmode != MBEDTLS_SSL_VERIFY_OPTIONAL) {
2800
0
            ret = MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE;
2801
0
        }
2802
2803
0
        goto exit;
2804
0
    }
2805
0
#endif /* MBEDTLS_SSL_SRV_C */
2806
2807
    /* Clear existing peer CRT structure in case we tried to
2808
     * reuse a session but it failed, and allocate a new one. */
2809
0
    ssl_clear_peer_cert(ssl->session_negotiate);
2810
2811
0
    chain = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
2812
0
    if (chain == NULL) {
2813
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed",
2814
0
                                  sizeof(mbedtls_x509_crt)));
2815
0
        mbedtls_ssl_send_alert_message(ssl,
2816
0
                                       MBEDTLS_SSL_ALERT_LEVEL_FATAL,
2817
0
                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
2818
2819
0
        ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
2820
0
        goto exit;
2821
0
    }
2822
0
    mbedtls_x509_crt_init(chain);
2823
2824
0
    ret = ssl_parse_certificate_chain(ssl, chain);
2825
0
    if (ret != 0) {
2826
0
        goto exit;
2827
0
    }
2828
2829
#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2830
    if (ssl->handshake->ecrs_enabled) {
2831
        ssl->handshake->ecrs_state = ssl_ecrs_crt_verify;
2832
    }
2833
2834
crt_verify:
2835
    if (ssl->handshake->ecrs_enabled) {
2836
        rs_ctx = &ssl->handshake->ecrs_ctx;
2837
    }
2838
#endif
2839
2840
0
    ret = ssl_parse_certificate_verify(ssl, authmode,
2841
0
                                       chain, rs_ctx);
2842
0
    if (ret != 0) {
2843
0
        goto exit;
2844
0
    }
2845
2846
0
#if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
2847
0
    {
2848
0
        unsigned char *crt_start, *pk_start;
2849
0
        size_t crt_len, pk_len;
2850
2851
        /* We parse the CRT chain without copying, so
2852
         * these pointers point into the input buffer,
2853
         * and are hence still valid after freeing the
2854
         * CRT chain. */
2855
2856
0
        crt_start = chain->raw.p;
2857
0
        crt_len   = chain->raw.len;
2858
2859
0
        pk_start = chain->pk_raw.p;
2860
0
        pk_len   = chain->pk_raw.len;
2861
2862
        /* Free the CRT structures before computing
2863
         * digest and copying the peer's public key. */
2864
0
        mbedtls_x509_crt_free(chain);
2865
0
        mbedtls_free(chain);
2866
0
        chain = NULL;
2867
2868
0
        ret = ssl_remember_peer_crt_digest(ssl, crt_start, crt_len);
2869
0
        if (ret != 0) {
2870
0
            goto exit;
2871
0
        }
2872
2873
0
        ret = ssl_remember_peer_pubkey(ssl, pk_start, pk_len);
2874
0
        if (ret != 0) {
2875
0
            goto exit;
2876
0
        }
2877
0
    }
2878
#else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2879
    /* Pass ownership to session structure. */
2880
    ssl->session_negotiate->peer_cert = chain;
2881
    chain = NULL;
2882
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
2883
2884
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse certificate"));
2885
2886
0
exit:
2887
2888
0
    if (ret == 0) {
2889
0
        ssl->state++;
2890
0
    }
2891
2892
#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
2893
    if (ret == MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) {
2894
        ssl->handshake->ecrs_peer_cert = chain;
2895
        chain = NULL;
2896
    }
2897
#endif
2898
2899
0
    if (chain != NULL) {
2900
0
        mbedtls_x509_crt_free(chain);
2901
0
        mbedtls_free(chain);
2902
0
    }
2903
2904
0
    return ret;
2905
0
}
2906
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
2907
2908
void mbedtls_ssl_optimize_checksum(mbedtls_ssl_context *ssl,
2909
                                   const mbedtls_ssl_ciphersuite_t *ciphersuite_info)
2910
0
{
2911
0
    ((void) ciphersuite_info);
2912
2913
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2914
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
2915
    if (ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3) {
2916
        ssl->handshake->update_checksum = ssl_update_checksum_md5sha1;
2917
    } else
2918
#endif
2919
0
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2920
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
2921
    if (ciphersuite_info->mac == MBEDTLS_MD_SHA384) {
2922
        ssl->handshake->update_checksum = ssl_update_checksum_sha384;
2923
    } else
2924
#endif
2925
0
#if defined(MBEDTLS_SHA256_C)
2926
0
    if (ciphersuite_info->mac != MBEDTLS_MD_SHA384) {
2927
0
        ssl->handshake->update_checksum = ssl_update_checksum_sha256;
2928
0
    } else
2929
0
#endif
2930
0
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2931
0
    {
2932
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("should never happen"));
2933
0
        return;
2934
0
    }
2935
0
}
2936
2937
void mbedtls_ssl_reset_checksum(mbedtls_ssl_context *ssl)
2938
0
{
2939
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2940
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
2941
    mbedtls_md5_starts_ret(&ssl->handshake->fin_md5);
2942
    mbedtls_sha1_starts_ret(&ssl->handshake->fin_sha1);
2943
#endif
2944
0
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2945
0
#if defined(MBEDTLS_SHA256_C)
2946
#if defined(MBEDTLS_USE_PSA_CRYPTO)
2947
    psa_hash_abort(&ssl->handshake->fin_sha256_psa);
2948
    psa_hash_setup(&ssl->handshake->fin_sha256_psa, PSA_ALG_SHA_256);
2949
#else
2950
0
    mbedtls_sha256_starts_ret(&ssl->handshake->fin_sha256, 0);
2951
0
#endif
2952
0
#endif
2953
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
2954
#if defined(MBEDTLS_USE_PSA_CRYPTO)
2955
    psa_hash_abort(&ssl->handshake->fin_sha384_psa);
2956
    psa_hash_setup(&ssl->handshake->fin_sha384_psa, PSA_ALG_SHA_384);
2957
#else
2958
    mbedtls_sha512_starts_ret(&ssl->handshake->fin_sha512, 1);
2959
#endif
2960
#endif
2961
0
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2962
0
}
2963
2964
static void ssl_update_checksum_start(mbedtls_ssl_context *ssl,
2965
                                      const unsigned char *buf, size_t len)
2966
287
{
2967
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2968
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
2969
    mbedtls_md5_update_ret(&ssl->handshake->fin_md5, buf, len);
2970
    mbedtls_sha1_update_ret(&ssl->handshake->fin_sha1, buf, len);
2971
#endif
2972
287
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
2973
287
#if defined(MBEDTLS_SHA256_C)
2974
#if defined(MBEDTLS_USE_PSA_CRYPTO)
2975
    psa_hash_update(&ssl->handshake->fin_sha256_psa, buf, len);
2976
#else
2977
287
    mbedtls_sha256_update_ret(&ssl->handshake->fin_sha256, buf, len);
2978
287
#endif
2979
287
#endif
2980
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
2981
#if defined(MBEDTLS_USE_PSA_CRYPTO)
2982
    psa_hash_update(&ssl->handshake->fin_sha384_psa, buf, len);
2983
#else
2984
    mbedtls_sha512_update_ret(&ssl->handshake->fin_sha512, buf, len);
2985
#endif
2986
#endif
2987
287
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
2988
287
}
2989
2990
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
2991
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
2992
static void ssl_update_checksum_md5sha1(mbedtls_ssl_context *ssl,
2993
                                        const unsigned char *buf, size_t len)
2994
{
2995
    mbedtls_md5_update_ret(&ssl->handshake->fin_md5, buf, len);
2996
    mbedtls_sha1_update_ret(&ssl->handshake->fin_sha1, buf, len);
2997
}
2998
#endif
2999
3000
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3001
#if defined(MBEDTLS_SHA256_C)
3002
static void ssl_update_checksum_sha256(mbedtls_ssl_context *ssl,
3003
                                       const unsigned char *buf, size_t len)
3004
0
{
3005
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3006
    psa_hash_update(&ssl->handshake->fin_sha256_psa, buf, len);
3007
#else
3008
0
    mbedtls_sha256_update_ret(&ssl->handshake->fin_sha256, buf, len);
3009
0
#endif
3010
0
}
3011
#endif
3012
3013
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
3014
static void ssl_update_checksum_sha384(mbedtls_ssl_context *ssl,
3015
                                       const unsigned char *buf, size_t len)
3016
{
3017
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3018
    psa_hash_update(&ssl->handshake->fin_sha384_psa, buf, len);
3019
#else
3020
    mbedtls_sha512_update_ret(&ssl->handshake->fin_sha512, buf, len);
3021
#endif
3022
}
3023
#endif
3024
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3025
3026
#if defined(MBEDTLS_SSL_PROTO_SSL3)
3027
static void ssl_calc_finished_ssl(
3028
    mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3029
{
3030
    const char *sender;
3031
    mbedtls_md5_context  md5;
3032
    mbedtls_sha1_context sha1;
3033
3034
    unsigned char padbuf[48];
3035
    unsigned char md5sum[16];
3036
    unsigned char sha1sum[20];
3037
3038
    mbedtls_ssl_session *session = ssl->session_negotiate;
3039
    if (!session) {
3040
        session = ssl->session;
3041
    }
3042
3043
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc  finished ssl"));
3044
3045
    mbedtls_md5_init(&md5);
3046
    mbedtls_sha1_init(&sha1);
3047
3048
    mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
3049
    mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
3050
3051
    /*
3052
     * SSLv3:
3053
     *   hash =
3054
     *      MD5( master + pad2 +
3055
     *          MD5( handshake + sender + master + pad1 ) )
3056
     *   + SHA1( master + pad2 +
3057
     *         SHA1( handshake + sender + master + pad1 ) )
3058
     */
3059
3060
#if !defined(MBEDTLS_MD5_ALT)
3061
    MBEDTLS_SSL_DEBUG_BUF(4, "finished  md5 state", (unsigned char *)
3062
                          md5.state, sizeof(md5.state));
3063
#endif
3064
3065
#if !defined(MBEDTLS_SHA1_ALT)
3066
    MBEDTLS_SSL_DEBUG_BUF(4, "finished sha1 state", (unsigned char *)
3067
                          sha1.state, sizeof(sha1.state));
3068
#endif
3069
3070
    sender = (from == MBEDTLS_SSL_IS_CLIENT) ? "CLNT"
3071
                                       : "SRVR";
3072
3073
    memset(padbuf, 0x36, 48);
3074
3075
    mbedtls_md5_update_ret(&md5, (const unsigned char *) sender, 4);
3076
    mbedtls_md5_update_ret(&md5, session->master, 48);
3077
    mbedtls_md5_update_ret(&md5, padbuf, 48);
3078
    mbedtls_md5_finish_ret(&md5, md5sum);
3079
3080
    mbedtls_sha1_update_ret(&sha1, (const unsigned char *) sender, 4);
3081
    mbedtls_sha1_update_ret(&sha1, session->master, 48);
3082
    mbedtls_sha1_update_ret(&sha1, padbuf, 40);
3083
    mbedtls_sha1_finish_ret(&sha1, sha1sum);
3084
3085
    memset(padbuf, 0x5C, 48);
3086
3087
    mbedtls_md5_starts_ret(&md5);
3088
    mbedtls_md5_update_ret(&md5, session->master, 48);
3089
    mbedtls_md5_update_ret(&md5, padbuf, 48);
3090
    mbedtls_md5_update_ret(&md5, md5sum, 16);
3091
    mbedtls_md5_finish_ret(&md5, buf);
3092
3093
    mbedtls_sha1_starts_ret(&sha1);
3094
    mbedtls_sha1_update_ret(&sha1, session->master, 48);
3095
    mbedtls_sha1_update_ret(&sha1, padbuf, 40);
3096
    mbedtls_sha1_update_ret(&sha1, sha1sum, 20);
3097
    mbedtls_sha1_finish_ret(&sha1, buf + 16);
3098
3099
    MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, 36);
3100
3101
    mbedtls_md5_free(&md5);
3102
    mbedtls_sha1_free(&sha1);
3103
3104
    mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3105
    mbedtls_platform_zeroize(md5sum, sizeof(md5sum));
3106
    mbedtls_platform_zeroize(sha1sum, sizeof(sha1sum));
3107
3108
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc  finished"));
3109
}
3110
#endif /* MBEDTLS_SSL_PROTO_SSL3 */
3111
3112
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
3113
static void ssl_calc_finished_tls(
3114
    mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3115
{
3116
    int len = 12;
3117
    const char *sender;
3118
    mbedtls_md5_context  md5;
3119
    mbedtls_sha1_context sha1;
3120
    unsigned char padbuf[36];
3121
3122
    mbedtls_ssl_session *session = ssl->session_negotiate;
3123
    if (!session) {
3124
        session = ssl->session;
3125
    }
3126
3127
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc  finished tls"));
3128
3129
    mbedtls_md5_init(&md5);
3130
    mbedtls_sha1_init(&sha1);
3131
3132
    mbedtls_md5_clone(&md5, &ssl->handshake->fin_md5);
3133
    mbedtls_sha1_clone(&sha1, &ssl->handshake->fin_sha1);
3134
3135
    /*
3136
     * TLSv1:
3137
     *   hash = PRF( master, finished_label,
3138
     *               MD5( handshake ) + SHA1( handshake ) )[0..11]
3139
     */
3140
3141
#if !defined(MBEDTLS_MD5_ALT)
3142
    MBEDTLS_SSL_DEBUG_BUF(4, "finished  md5 state", (unsigned char *)
3143
                          md5.state, sizeof(md5.state));
3144
#endif
3145
3146
#if !defined(MBEDTLS_SHA1_ALT)
3147
    MBEDTLS_SSL_DEBUG_BUF(4, "finished sha1 state", (unsigned char *)
3148
                          sha1.state, sizeof(sha1.state));
3149
#endif
3150
3151
    sender = (from == MBEDTLS_SSL_IS_CLIENT)
3152
             ? "client finished"
3153
             : "server finished";
3154
3155
    mbedtls_md5_finish_ret(&md5, padbuf);
3156
    mbedtls_sha1_finish_ret(&sha1, padbuf + 16);
3157
3158
    ssl->handshake->tls_prf(session->master, 48, sender,
3159
                            padbuf, 36, buf, len);
3160
3161
    MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, len);
3162
3163
    mbedtls_md5_free(&md5);
3164
    mbedtls_sha1_free(&sha1);
3165
3166
    mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3167
3168
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc  finished"));
3169
}
3170
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
3171
3172
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3173
#if defined(MBEDTLS_SHA256_C)
3174
static void ssl_calc_finished_tls_sha256(
3175
    mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3176
0
{
3177
0
    int len = 12;
3178
0
    const char *sender;
3179
0
    unsigned char padbuf[32];
3180
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3181
    size_t hash_size;
3182
    psa_hash_operation_t sha256_psa = PSA_HASH_OPERATION_INIT;
3183
    psa_status_t status;
3184
#else
3185
0
    mbedtls_sha256_context sha256;
3186
0
#endif
3187
3188
0
    mbedtls_ssl_session *session = ssl->session_negotiate;
3189
0
    if (!session) {
3190
0
        session = ssl->session;
3191
0
    }
3192
3193
0
    sender = (from == MBEDTLS_SSL_IS_CLIENT)
3194
0
             ? "client finished"
3195
0
             : "server finished";
3196
3197
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3198
    sha256_psa = psa_hash_operation_init();
3199
3200
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc PSA finished tls sha256"));
3201
3202
    status = psa_hash_clone(&ssl->handshake->fin_sha256_psa, &sha256_psa);
3203
    if (status != PSA_SUCCESS) {
3204
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
3205
        return;
3206
    }
3207
3208
    status = psa_hash_finish(&sha256_psa, padbuf, sizeof(padbuf), &hash_size);
3209
    if (status != PSA_SUCCESS) {
3210
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
3211
        return;
3212
    }
3213
    MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated padbuf", padbuf, 32);
3214
#else
3215
3216
0
    mbedtls_sha256_init(&sha256);
3217
3218
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc  finished tls sha256"));
3219
3220
0
    mbedtls_sha256_clone(&sha256, &ssl->handshake->fin_sha256);
3221
3222
    /*
3223
     * TLSv1.2:
3224
     *   hash = PRF( master, finished_label,
3225
     *               Hash( handshake ) )[0.11]
3226
     */
3227
3228
0
#if !defined(MBEDTLS_SHA256_ALT)
3229
0
    MBEDTLS_SSL_DEBUG_BUF(4, "finished sha2 state", (unsigned char *)
3230
0
                          sha256.state, sizeof(sha256.state));
3231
0
#endif
3232
3233
0
    mbedtls_sha256_finish_ret(&sha256, padbuf);
3234
0
    mbedtls_sha256_free(&sha256);
3235
0
#endif /* MBEDTLS_USE_PSA_CRYPTO */
3236
3237
0
    ssl->handshake->tls_prf(session->master, 48, sender,
3238
0
                            padbuf, 32, buf, len);
3239
3240
0
    MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, len);
3241
3242
0
    mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3243
3244
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc  finished"));
3245
0
}
3246
#endif /* MBEDTLS_SHA256_C */
3247
3248
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
3249
3250
static void ssl_calc_finished_tls_sha384(
3251
    mbedtls_ssl_context *ssl, unsigned char *buf, int from)
3252
{
3253
    int len = 12;
3254
    const char *sender;
3255
    unsigned char padbuf[48];
3256
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3257
    size_t hash_size;
3258
    psa_hash_operation_t sha384_psa = PSA_HASH_OPERATION_INIT;
3259
    psa_status_t status;
3260
#else
3261
    mbedtls_sha512_context sha512;
3262
#endif
3263
3264
    mbedtls_ssl_session *session = ssl->session_negotiate;
3265
    if (!session) {
3266
        session = ssl->session;
3267
    }
3268
3269
    sender = (from == MBEDTLS_SSL_IS_CLIENT)
3270
                ? "client finished"
3271
                : "server finished";
3272
3273
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3274
    sha384_psa = psa_hash_operation_init();
3275
3276
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc PSA finished tls sha384"));
3277
3278
    status = psa_hash_clone(&ssl->handshake->fin_sha384_psa, &sha384_psa);
3279
    if (status != PSA_SUCCESS) {
3280
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash clone failed"));
3281
        return;
3282
    }
3283
3284
    status = psa_hash_finish(&sha384_psa, padbuf, sizeof(padbuf), &hash_size);
3285
    if (status != PSA_SUCCESS) {
3286
        MBEDTLS_SSL_DEBUG_MSG(2, ("PSA hash finish failed"));
3287
        return;
3288
    }
3289
    MBEDTLS_SSL_DEBUG_BUF(3, "PSA calculated padbuf", padbuf, 48);
3290
#else
3291
    mbedtls_sha512_init(&sha512);
3292
3293
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> calc  finished tls sha384"));
3294
3295
    mbedtls_sha512_clone(&sha512, &ssl->handshake->fin_sha512);
3296
3297
    /*
3298
     * TLSv1.2:
3299
     *   hash = PRF( master, finished_label,
3300
     *               Hash( handshake ) )[0.11]
3301
     */
3302
3303
#if !defined(MBEDTLS_SHA512_ALT)
3304
    MBEDTLS_SSL_DEBUG_BUF(4, "finished sha512 state", (unsigned char *)
3305
                          sha512.state, sizeof(sha512.state));
3306
#endif
3307
    /* mbedtls_sha512_finish_ret's output parameter is declared as a
3308
     * 64-byte buffer, but since we're using SHA-384, we know that the
3309
     * output fits in 48 bytes. This is correct C, but GCC 11.1 warns
3310
     * about it.
3311
     */
3312
#if defined(__GNUC__) && __GNUC__ >= 11
3313
#pragma GCC diagnostic push
3314
#pragma GCC diagnostic ignored "-Wstringop-overflow"
3315
#endif
3316
    mbedtls_sha512_finish_ret(&sha512, padbuf);
3317
#if defined(__GNUC__) && __GNUC__ >= 11
3318
#pragma GCC diagnostic pop
3319
#endif
3320
3321
    mbedtls_sha512_free(&sha512);
3322
#endif
3323
3324
    ssl->handshake->tls_prf(session->master, 48, sender,
3325
                            padbuf, 48, buf, len);
3326
3327
    MBEDTLS_SSL_DEBUG_BUF(3, "calc finished result", buf, len);
3328
3329
    mbedtls_platform_zeroize(padbuf, sizeof(padbuf));
3330
3331
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= calc  finished"));
3332
}
3333
#endif /* MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384 */
3334
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3335
3336
void mbedtls_ssl_handshake_wrapup_free_hs_transform(mbedtls_ssl_context *ssl)
3337
0
{
3338
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("=> handshake wrapup: final free"));
3339
3340
    /*
3341
     * Free our handshake params
3342
     */
3343
0
    mbedtls_ssl_handshake_free(ssl);
3344
0
    mbedtls_free(ssl->handshake);
3345
0
    ssl->handshake = NULL;
3346
3347
    /*
3348
     * Free the previous transform and switch in the current one
3349
     */
3350
0
    if (ssl->transform) {
3351
0
        mbedtls_ssl_transform_free(ssl->transform);
3352
0
        mbedtls_free(ssl->transform);
3353
0
    }
3354
0
    ssl->transform = ssl->transform_negotiate;
3355
0
    ssl->transform_negotiate = NULL;
3356
3357
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("<= handshake wrapup: final free"));
3358
0
}
3359
3360
void mbedtls_ssl_handshake_wrapup(mbedtls_ssl_context *ssl)
3361
0
{
3362
0
    int resume = ssl->handshake->resume;
3363
3364
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("=> handshake wrapup"));
3365
3366
#if defined(MBEDTLS_SSL_RENEGOTIATION)
3367
    if (ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
3368
        ssl->renego_status =  MBEDTLS_SSL_RENEGOTIATION_DONE;
3369
        ssl->renego_records_seen = 0;
3370
    }
3371
#endif
3372
3373
    /*
3374
     * Free the previous session and switch in the current one
3375
     */
3376
0
    if (ssl->session) {
3377
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
3378
        /* RFC 7366 3.1: keep the EtM state */
3379
        ssl->session_negotiate->encrypt_then_mac =
3380
            ssl->session->encrypt_then_mac;
3381
#endif
3382
3383
0
        mbedtls_ssl_session_free(ssl->session);
3384
0
        mbedtls_free(ssl->session);
3385
0
    }
3386
0
    ssl->session = ssl->session_negotiate;
3387
0
    ssl->session_negotiate = NULL;
3388
3389
    /*
3390
     * Add cache entry
3391
     */
3392
0
    if (ssl->conf->f_set_cache != NULL &&
3393
0
        ssl->session->id_len != 0 &&
3394
0
        resume == 0) {
3395
0
        if (ssl->conf->f_set_cache(ssl->conf->p_cache, ssl->session) != 0) {
3396
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("cache did not store session"));
3397
0
        }
3398
0
    }
3399
3400
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3401
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3402
0
        ssl->handshake->flight != NULL) {
3403
        /* Cancel handshake timer */
3404
0
        mbedtls_ssl_set_timer(ssl, 0);
3405
3406
        /* Keep last flight around in case we need to resend it:
3407
         * we need the handshake and transform structures for that */
3408
0
        MBEDTLS_SSL_DEBUG_MSG(3, ("skip freeing handshake and transform"));
3409
0
    } else
3410
0
#endif
3411
0
    mbedtls_ssl_handshake_wrapup_free_hs_transform(ssl);
3412
3413
0
    ssl->state++;
3414
3415
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("<= handshake wrapup"));
3416
0
}
3417
3418
int mbedtls_ssl_write_finished(mbedtls_ssl_context *ssl)
3419
0
{
3420
0
    int ret, hash_len;
3421
3422
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write finished"));
3423
3424
0
    mbedtls_ssl_update_out_pointers(ssl, ssl->transform_negotiate);
3425
3426
0
    ssl->handshake->calc_finished(ssl, ssl->out_msg + 4, ssl->conf->endpoint);
3427
3428
    /*
3429
     * RFC 5246 7.4.9 (Page 63) says 12 is the default length and ciphersuites
3430
     * may define some other value. Currently (early 2016), no defined
3431
     * ciphersuite does this (and this is unlikely to change as activity has
3432
     * moved to TLS 1.3 now) so we can keep the hardcoded 12 here.
3433
     */
3434
0
    hash_len = (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) ? 36 : 12;
3435
3436
#if defined(MBEDTLS_SSL_RENEGOTIATION)
3437
    ssl->verify_data_len = hash_len;
3438
    memcpy(ssl->own_verify_data, ssl->out_msg + 4, hash_len);
3439
#endif
3440
3441
0
    ssl->out_msglen  = 4 + hash_len;
3442
0
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
3443
0
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_FINISHED;
3444
3445
    /*
3446
     * In case of session resuming, invert the client and server
3447
     * ChangeCipherSpec messages order.
3448
     */
3449
0
    if (ssl->handshake->resume != 0) {
3450
0
#if defined(MBEDTLS_SSL_CLI_C)
3451
0
        if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
3452
0
            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3453
0
        }
3454
0
#endif
3455
0
#if defined(MBEDTLS_SSL_SRV_C)
3456
0
        if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
3457
0
            ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
3458
0
        }
3459
0
#endif
3460
0
    } else {
3461
0
        ssl->state++;
3462
0
    }
3463
3464
    /*
3465
     * Switch to our negotiated transform and session parameters for outbound
3466
     * data.
3467
     */
3468
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("switching to new transform spec for outbound data"));
3469
3470
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3471
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3472
0
        unsigned char i;
3473
3474
        /* Remember current epoch settings for resending */
3475
0
        ssl->handshake->alt_transform_out = ssl->transform_out;
3476
0
        memcpy(ssl->handshake->alt_out_ctr, ssl->cur_out_ctr, 8);
3477
3478
        /* Set sequence_number to zero */
3479
0
        memset(ssl->cur_out_ctr + 2, 0, 6);
3480
3481
        /* Increment epoch */
3482
0
        for (i = 2; i > 0; i--) {
3483
0
            if (++ssl->cur_out_ctr[i - 1] != 0) {
3484
0
                break;
3485
0
            }
3486
0
        }
3487
3488
        /* The loop goes to its end iff the counter is wrapping */
3489
0
        if (i == 0) {
3490
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("DTLS epoch would wrap"));
3491
0
            return MBEDTLS_ERR_SSL_COUNTER_WRAPPING;
3492
0
        }
3493
0
    } else
3494
0
#endif /* MBEDTLS_SSL_PROTO_DTLS */
3495
0
    memset(ssl->cur_out_ctr, 0, 8);
3496
3497
0
    ssl->transform_out = ssl->transform_negotiate;
3498
0
    ssl->session_out = ssl->session_negotiate;
3499
3500
#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3501
    if (mbedtls_ssl_hw_record_activate != NULL) {
3502
        if ((ret = mbedtls_ssl_hw_record_activate(ssl, MBEDTLS_SSL_CHANNEL_OUTBOUND)) != 0) {
3503
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_hw_record_activate", ret);
3504
            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
3505
        }
3506
    }
3507
#endif
3508
3509
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3510
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3511
0
        mbedtls_ssl_send_flight_completed(ssl);
3512
0
    }
3513
0
#endif
3514
3515
0
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
3516
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
3517
0
        return ret;
3518
0
    }
3519
3520
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3521
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
3522
0
        (ret = mbedtls_ssl_flight_transmit(ssl)) != 0) {
3523
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_flight_transmit", ret);
3524
0
        return ret;
3525
0
    }
3526
0
#endif
3527
3528
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write finished"));
3529
3530
0
    return 0;
3531
0
}
3532
3533
#if defined(MBEDTLS_SSL_PROTO_SSL3)
3534
#define SSL_MAX_HASH_LEN 36
3535
#else
3536
#define SSL_MAX_HASH_LEN 12
3537
#endif
3538
3539
int mbedtls_ssl_parse_finished(mbedtls_ssl_context *ssl)
3540
0
{
3541
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3542
0
    unsigned int hash_len;
3543
0
    unsigned char buf[SSL_MAX_HASH_LEN];
3544
3545
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> parse finished"));
3546
3547
    /* There is currently no ciphersuite using another length with TLS 1.2 */
3548
#if defined(MBEDTLS_SSL_PROTO_SSL3)
3549
    if (ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0) {
3550
        hash_len = 36;
3551
    } else
3552
#endif
3553
0
    hash_len = 12;
3554
3555
0
    ssl->handshake->calc_finished(ssl, buf, ssl->conf->endpoint ^ 1);
3556
3557
0
    if ((ret = mbedtls_ssl_read_record(ssl, 1)) != 0) {
3558
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_read_record", ret);
3559
0
        goto exit;
3560
0
    }
3561
3562
0
    if (ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE) {
3563
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
3564
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3565
0
                                       MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE);
3566
0
        ret = MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE;
3567
0
        goto exit;
3568
0
    }
3569
3570
0
    if (ssl->in_msg[0] != MBEDTLS_SSL_HS_FINISHED ||
3571
0
        ssl->in_hslen  != mbedtls_ssl_hs_hdr_len(ssl) + hash_len) {
3572
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
3573
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3574
0
                                       MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR);
3575
0
        ret = MBEDTLS_ERR_SSL_BAD_HS_FINISHED;
3576
0
        goto exit;
3577
0
    }
3578
3579
0
    if (mbedtls_ct_memcmp(ssl->in_msg + mbedtls_ssl_hs_hdr_len(ssl),
3580
0
                          buf, hash_len) != 0) {
3581
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("bad finished message"));
3582
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
3583
0
                                       MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR);
3584
0
        ret = MBEDTLS_ERR_SSL_BAD_HS_FINISHED;
3585
0
        goto exit;
3586
0
    }
3587
3588
#if defined(MBEDTLS_SSL_RENEGOTIATION)
3589
    ssl->verify_data_len = hash_len;
3590
    memcpy(ssl->peer_verify_data, buf, hash_len);
3591
#endif
3592
3593
0
    if (ssl->handshake->resume != 0) {
3594
0
#if defined(MBEDTLS_SSL_CLI_C)
3595
0
        if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
3596
0
            ssl->state = MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC;
3597
0
        }
3598
0
#endif
3599
0
#if defined(MBEDTLS_SSL_SRV_C)
3600
0
        if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
3601
0
            ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP;
3602
0
        }
3603
0
#endif
3604
0
    } else {
3605
0
        ssl->state++;
3606
0
    }
3607
3608
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3609
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3610
0
        mbedtls_ssl_recv_flight_completed(ssl);
3611
0
    }
3612
0
#endif
3613
3614
0
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= parse finished"));
3615
3616
0
exit:
3617
0
    mbedtls_platform_zeroize(buf, hash_len);
3618
0
    return ret;
3619
0
}
3620
3621
static void ssl_handshake_params_init(mbedtls_ssl_handshake_params *handshake)
3622
4.39k
{
3623
4.39k
    memset(handshake, 0, sizeof(mbedtls_ssl_handshake_params));
3624
3625
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
3626
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
3627
    mbedtls_md5_init(&handshake->fin_md5);
3628
    mbedtls_sha1_init(&handshake->fin_sha1);
3629
    mbedtls_md5_starts_ret(&handshake->fin_md5);
3630
    mbedtls_sha1_starts_ret(&handshake->fin_sha1);
3631
#endif
3632
4.39k
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
3633
4.39k
#if defined(MBEDTLS_SHA256_C)
3634
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3635
    handshake->fin_sha256_psa = psa_hash_operation_init();
3636
    psa_hash_setup(&handshake->fin_sha256_psa, PSA_ALG_SHA_256);
3637
#else
3638
4.39k
    mbedtls_sha256_init(&handshake->fin_sha256);
3639
4.39k
    mbedtls_sha256_starts_ret(&handshake->fin_sha256, 0);
3640
4.39k
#endif
3641
4.39k
#endif
3642
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
3643
#if defined(MBEDTLS_USE_PSA_CRYPTO)
3644
    handshake->fin_sha384_psa = psa_hash_operation_init();
3645
    psa_hash_setup(&handshake->fin_sha384_psa, PSA_ALG_SHA_384);
3646
#else
3647
    mbedtls_sha512_init(&handshake->fin_sha512);
3648
    mbedtls_sha512_starts_ret(&handshake->fin_sha512, 1);
3649
#endif
3650
#endif
3651
4.39k
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
3652
3653
4.39k
    handshake->update_checksum = ssl_update_checksum_start;
3654
3655
4.39k
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
3656
4.39k
    defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
3657
4.39k
    mbedtls_ssl_sig_hash_set_init(&handshake->hash_algs);
3658
4.39k
#endif
3659
3660
#if defined(MBEDTLS_DHM_C)
3661
    mbedtls_dhm_init(&handshake->dhm_ctx);
3662
#endif
3663
4.39k
#if defined(MBEDTLS_ECDH_C)
3664
4.39k
    mbedtls_ecdh_init(&handshake->ecdh_ctx);
3665
4.39k
#endif
3666
4.39k
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
3667
4.39k
    mbedtls_ecjpake_init(&handshake->ecjpake_ctx);
3668
4.39k
#if defined(MBEDTLS_SSL_CLI_C)
3669
4.39k
    handshake->ecjpake_cache = NULL;
3670
4.39k
    handshake->ecjpake_cache_len = 0;
3671
4.39k
#endif
3672
4.39k
#endif
3673
3674
#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
3675
    mbedtls_x509_crt_restart_init(&handshake->ecrs_ctx);
3676
#endif
3677
3678
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
3679
    handshake->sni_authmode = MBEDTLS_SSL_VERIFY_UNSET;
3680
#endif
3681
3682
4.39k
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
3683
4.39k
    !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
3684
4.39k
    mbedtls_pk_init(&handshake->peer_pubkey);
3685
4.39k
#endif
3686
4.39k
}
3687
3688
void mbedtls_ssl_transform_init(mbedtls_ssl_transform *transform)
3689
4.39k
{
3690
4.39k
    memset(transform, 0, sizeof(mbedtls_ssl_transform));
3691
3692
4.39k
    mbedtls_cipher_init(&transform->cipher_ctx_enc);
3693
4.39k
    mbedtls_cipher_init(&transform->cipher_ctx_dec);
3694
3695
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
3696
    mbedtls_md_init(&transform->md_ctx_enc);
3697
    mbedtls_md_init(&transform->md_ctx_dec);
3698
#endif
3699
4.39k
}
3700
3701
void mbedtls_ssl_session_init(mbedtls_ssl_session *session)
3702
4.39k
{
3703
4.39k
    memset(session, 0, sizeof(mbedtls_ssl_session));
3704
4.39k
}
3705
3706
MBEDTLS_CHECK_RETURN_CRITICAL
3707
static int ssl_handshake_init(mbedtls_ssl_context *ssl)
3708
4.39k
{
3709
    /* Clear old handshake information if present */
3710
4.39k
    if (ssl->transform_negotiate) {
3711
0
        mbedtls_ssl_transform_free(ssl->transform_negotiate);
3712
0
    }
3713
4.39k
    if (ssl->session_negotiate) {
3714
0
        mbedtls_ssl_session_free(ssl->session_negotiate);
3715
0
    }
3716
4.39k
    if (ssl->handshake) {
3717
0
        mbedtls_ssl_handshake_free(ssl);
3718
0
    }
3719
3720
    /*
3721
     * Either the pointers are now NULL or cleared properly and can be freed.
3722
     * Now allocate missing structures.
3723
     */
3724
4.39k
    if (ssl->transform_negotiate == NULL) {
3725
4.39k
        ssl->transform_negotiate = mbedtls_calloc(1, sizeof(mbedtls_ssl_transform));
3726
4.39k
    }
3727
3728
4.39k
    if (ssl->session_negotiate == NULL) {
3729
4.39k
        ssl->session_negotiate = mbedtls_calloc(1, sizeof(mbedtls_ssl_session));
3730
4.39k
    }
3731
3732
4.39k
    if (ssl->handshake == NULL) {
3733
4.39k
        ssl->handshake = mbedtls_calloc(1, sizeof(mbedtls_ssl_handshake_params));
3734
4.39k
    }
3735
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3736
    /* If the buffers are too small - reallocate */
3737
3738
    handle_buffer_resizing(ssl, 0, MBEDTLS_SSL_IN_BUFFER_LEN,
3739
                           MBEDTLS_SSL_OUT_BUFFER_LEN);
3740
#endif
3741
3742
    /* All pointers should exist and can be directly freed without issue */
3743
4.39k
    if (ssl->handshake == NULL ||
3744
4.39k
        ssl->transform_negotiate == NULL ||
3745
4.39k
        ssl->session_negotiate == NULL) {
3746
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("alloc() of ssl sub-contexts failed"));
3747
3748
0
        mbedtls_free(ssl->handshake);
3749
0
        mbedtls_free(ssl->transform_negotiate);
3750
0
        mbedtls_free(ssl->session_negotiate);
3751
3752
0
        ssl->handshake = NULL;
3753
0
        ssl->transform_negotiate = NULL;
3754
0
        ssl->session_negotiate = NULL;
3755
3756
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
3757
0
    }
3758
3759
    /* Initialize structures */
3760
4.39k
    mbedtls_ssl_session_init(ssl->session_negotiate);
3761
4.39k
    mbedtls_ssl_transform_init(ssl->transform_negotiate);
3762
4.39k
    ssl_handshake_params_init(ssl->handshake);
3763
3764
4.39k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3765
4.39k
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
3766
4.38k
        ssl->handshake->alt_transform_out = ssl->transform_out;
3767
3768
4.38k
        if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
3769
0
            ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_PREPARING;
3770
4.38k
        } else {
3771
4.38k
            ssl->handshake->retransmit_state = MBEDTLS_SSL_RETRANS_WAITING;
3772
4.38k
        }
3773
3774
4.38k
        mbedtls_ssl_set_timer(ssl, 0);
3775
4.38k
    }
3776
4.39k
#endif
3777
3778
4.39k
    return 0;
3779
4.39k
}
3780
3781
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
3782
/* Dummy cookie callbacks for defaults */
3783
MBEDTLS_CHECK_RETURN_CRITICAL
3784
static int ssl_cookie_write_dummy(void *ctx,
3785
                                  unsigned char **p, unsigned char *end,
3786
                                  const unsigned char *cli_id, size_t cli_id_len)
3787
0
{
3788
0
    ((void) ctx);
3789
0
    ((void) p);
3790
0
    ((void) end);
3791
0
    ((void) cli_id);
3792
0
    ((void) cli_id_len);
3793
3794
0
    return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3795
0
}
3796
3797
MBEDTLS_CHECK_RETURN_CRITICAL
3798
static int ssl_cookie_check_dummy(void *ctx,
3799
                                  const unsigned char *cookie, size_t cookie_len,
3800
                                  const unsigned char *cli_id, size_t cli_id_len)
3801
0
{
3802
0
    ((void) ctx);
3803
0
    ((void) cookie);
3804
0
    ((void) cookie_len);
3805
0
    ((void) cli_id);
3806
0
    ((void) cli_id_len);
3807
3808
0
    return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
3809
0
}
3810
#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
3811
3812
/*
3813
 * Initialize an SSL context
3814
 */
3815
void mbedtls_ssl_init(mbedtls_ssl_context *ssl)
3816
4.44k
{
3817
4.44k
    memset(ssl, 0, sizeof(mbedtls_ssl_context));
3818
4.44k
}
3819
3820
/*
3821
 * Setup an SSL context
3822
 */
3823
3824
int mbedtls_ssl_setup(mbedtls_ssl_context *ssl,
3825
                      const mbedtls_ssl_config *conf)
3826
4.44k
{
3827
4.44k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3828
4.44k
    size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
3829
4.44k
    size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
3830
3831
4.44k
    ssl->conf = conf;
3832
3833
    /*
3834
     * Prepare base structures
3835
     */
3836
3837
    /* Set to NULL in case of an error condition */
3838
4.44k
    ssl->out_buf = NULL;
3839
3840
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3841
    ssl->in_buf_len = in_buf_len;
3842
#endif
3843
4.44k
    ssl->in_buf = mbedtls_calloc(1, in_buf_len);
3844
4.44k
    if (ssl->in_buf == NULL) {
3845
52
        MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", in_buf_len));
3846
52
        ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
3847
52
        goto error;
3848
52
    }
3849
3850
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3851
    ssl->out_buf_len = out_buf_len;
3852
#endif
3853
4.39k
    ssl->out_buf = mbedtls_calloc(1, out_buf_len);
3854
4.39k
    if (ssl->out_buf == NULL) {
3855
1
        MBEDTLS_SSL_DEBUG_MSG(1, ("alloc(%" MBEDTLS_PRINTF_SIZET " bytes) failed", out_buf_len));
3856
1
        ret = MBEDTLS_ERR_SSL_ALLOC_FAILED;
3857
1
        goto error;
3858
1
    }
3859
3860
4.39k
    mbedtls_ssl_reset_in_out_pointers(ssl);
3861
3862
#if defined(MBEDTLS_SSL_DTLS_SRTP)
3863
    memset(&ssl->dtls_srtp_info, 0, sizeof(ssl->dtls_srtp_info));
3864
#endif
3865
3866
4.39k
    if ((ret = ssl_handshake_init(ssl)) != 0) {
3867
0
        goto error;
3868
0
    }
3869
3870
4.39k
    return 0;
3871
3872
53
error:
3873
53
    mbedtls_free(ssl->in_buf);
3874
53
    mbedtls_free(ssl->out_buf);
3875
3876
53
    ssl->conf = NULL;
3877
3878
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3879
    ssl->in_buf_len = 0;
3880
    ssl->out_buf_len = 0;
3881
#endif
3882
53
    ssl->in_buf = NULL;
3883
53
    ssl->out_buf = NULL;
3884
3885
53
    ssl->in_hdr = NULL;
3886
53
    ssl->in_ctr = NULL;
3887
53
    ssl->in_len = NULL;
3888
53
    ssl->in_iv = NULL;
3889
53
    ssl->in_msg = NULL;
3890
3891
53
    ssl->out_hdr = NULL;
3892
53
    ssl->out_ctr = NULL;
3893
53
    ssl->out_len = NULL;
3894
53
    ssl->out_iv = NULL;
3895
53
    ssl->out_msg = NULL;
3896
3897
53
    return ret;
3898
4.39k
}
3899
3900
/*
3901
 * Reset an initialized and used SSL context for re-use while retaining
3902
 * all application-set variables, function pointers and data.
3903
 *
3904
 * If partial is non-zero, keep data in the input buffer and client ID.
3905
 * (Use when a DTLS client reconnects from the same port.)
3906
 */
3907
int mbedtls_ssl_session_reset_int(mbedtls_ssl_context *ssl, int partial)
3908
0
{
3909
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
3910
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
3911
    size_t in_buf_len = ssl->in_buf_len;
3912
    size_t out_buf_len = ssl->out_buf_len;
3913
#else
3914
0
    size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
3915
0
    size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
3916
0
#endif
3917
3918
0
#if !defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) ||     \
3919
0
    !defined(MBEDTLS_SSL_SRV_C)
3920
0
    ((void) partial);
3921
0
#endif
3922
3923
0
    ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
3924
3925
    /* Cancel any possibly running timer */
3926
0
    mbedtls_ssl_set_timer(ssl, 0);
3927
3928
#if defined(MBEDTLS_SSL_RENEGOTIATION)
3929
    ssl->renego_status = MBEDTLS_SSL_INITIAL_HANDSHAKE;
3930
    ssl->renego_records_seen = 0;
3931
3932
    ssl->verify_data_len = 0;
3933
    memset(ssl->own_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN);
3934
    memset(ssl->peer_verify_data, 0, MBEDTLS_SSL_VERIFY_DATA_MAX_LEN);
3935
#endif
3936
0
    ssl->secure_renegotiation = MBEDTLS_SSL_LEGACY_RENEGOTIATION;
3937
3938
0
    ssl->in_offt = NULL;
3939
0
    mbedtls_ssl_reset_in_out_pointers(ssl);
3940
3941
0
    ssl->in_msgtype = 0;
3942
0
    ssl->in_msglen = 0;
3943
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
3944
0
    ssl->next_record_offset = 0;
3945
0
    ssl->in_epoch = 0;
3946
0
#endif
3947
0
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
3948
0
    mbedtls_ssl_dtls_replay_reset(ssl);
3949
0
#endif
3950
3951
0
    ssl->in_hslen = 0;
3952
0
    ssl->nb_zero = 0;
3953
3954
0
    ssl->keep_current_message = 0;
3955
3956
0
    ssl->out_msgtype = 0;
3957
0
    ssl->out_msglen = 0;
3958
0
    ssl->out_left = 0;
3959
#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
3960
    if (ssl->split_done != MBEDTLS_SSL_CBC_RECORD_SPLITTING_DISABLED) {
3961
        ssl->split_done = 0;
3962
    }
3963
#endif
3964
3965
0
    memset(ssl->cur_out_ctr, 0, sizeof(ssl->cur_out_ctr));
3966
3967
0
    ssl->transform_in = NULL;
3968
0
    ssl->transform_out = NULL;
3969
3970
0
    ssl->session_in = NULL;
3971
0
    ssl->session_out = NULL;
3972
3973
0
    memset(ssl->out_buf, 0, out_buf_len);
3974
3975
0
    int clear_in_buf = 1;
3976
#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && defined(MBEDTLS_SSL_SRV_C)
3977
    if (partial != 0) {
3978
        clear_in_buf = 0;
3979
    }
3980
#endif /* MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE && MBEDTLS_SSL_SRV_C */
3981
0
    if (clear_in_buf) {
3982
0
        ssl->in_left = 0;
3983
0
        memset(ssl->in_buf, 0, in_buf_len);
3984
0
    }
3985
3986
#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
3987
    if (mbedtls_ssl_hw_record_reset != NULL) {
3988
        MBEDTLS_SSL_DEBUG_MSG(2, ("going for mbedtls_ssl_hw_record_reset()"));
3989
        if ((ret = mbedtls_ssl_hw_record_reset(ssl)) != 0) {
3990
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_hw_record_reset", ret);
3991
            return MBEDTLS_ERR_SSL_HW_ACCEL_FAILED;
3992
        }
3993
    }
3994
#endif
3995
3996
0
    if (ssl->transform) {
3997
0
        mbedtls_ssl_transform_free(ssl->transform);
3998
0
        mbedtls_free(ssl->transform);
3999
0
        ssl->transform = NULL;
4000
0
    }
4001
4002
0
    if (ssl->session) {
4003
0
        mbedtls_ssl_session_free(ssl->session);
4004
0
        mbedtls_free(ssl->session);
4005
0
        ssl->session = NULL;
4006
0
    }
4007
4008
#if defined(MBEDTLS_SSL_ALPN)
4009
    ssl->alpn_chosen = NULL;
4010
#endif
4011
4012
0
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
4013
0
    int free_cli_id = 1;
4014
#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE)
4015
    if (partial != 0) {
4016
        free_cli_id = 0;
4017
    }
4018
#endif
4019
0
    if (free_cli_id) {
4020
0
        mbedtls_free(ssl->cli_id);
4021
0
        ssl->cli_id = NULL;
4022
0
        ssl->cli_id_len = 0;
4023
0
    }
4024
0
#endif
4025
4026
0
    if ((ret = ssl_handshake_init(ssl)) != 0) {
4027
0
        return ret;
4028
0
    }
4029
4030
0
    return 0;
4031
0
}
4032
4033
/*
4034
 * Reset an initialized and used SSL context for re-use while retaining
4035
 * all application-set variables, function pointers and data.
4036
 */
4037
int mbedtls_ssl_session_reset(mbedtls_ssl_context *ssl)
4038
0
{
4039
0
    return mbedtls_ssl_session_reset_int(ssl, 0);
4040
0
}
4041
4042
/*
4043
 * SSL set accessors
4044
 */
4045
void mbedtls_ssl_conf_endpoint(mbedtls_ssl_config *conf, int endpoint)
4046
4.38k
{
4047
4.38k
    conf->endpoint   = endpoint;
4048
4.38k
}
4049
4050
void mbedtls_ssl_conf_transport(mbedtls_ssl_config *conf, int transport)
4051
4.38k
{
4052
4.38k
    conf->transport = transport;
4053
4.38k
}
4054
4055
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
4056
void mbedtls_ssl_conf_dtls_anti_replay(mbedtls_ssl_config *conf, char mode)
4057
0
{
4058
0
    conf->anti_replay = mode;
4059
0
}
4060
#endif
4061
4062
#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
4063
void mbedtls_ssl_conf_dtls_badmac_limit(mbedtls_ssl_config *conf, unsigned limit)
4064
{
4065
    conf->badmac_limit = limit;
4066
}
4067
#endif
4068
4069
#if defined(MBEDTLS_SSL_PROTO_DTLS)
4070
4071
void mbedtls_ssl_set_datagram_packing(mbedtls_ssl_context *ssl,
4072
                                      unsigned allow_packing)
4073
0
{
4074
0
    ssl->disable_datagram_packing = !allow_packing;
4075
0
}
4076
4077
void mbedtls_ssl_conf_handshake_timeout(mbedtls_ssl_config *conf,
4078
                                        uint32_t min, uint32_t max)
4079
4.38k
{
4080
4.38k
    conf->hs_timeout_min = min;
4081
4.38k
    conf->hs_timeout_max = max;
4082
4.38k
}
4083
#endif
4084
4085
void mbedtls_ssl_conf_authmode(mbedtls_ssl_config *conf, int authmode)
4086
4.44k
{
4087
4.44k
    conf->authmode   = authmode;
4088
4.44k
}
4089
4090
#if defined(MBEDTLS_X509_CRT_PARSE_C)
4091
void mbedtls_ssl_conf_verify(mbedtls_ssl_config *conf,
4092
                             int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
4093
                             void *p_vrfy)
4094
0
{
4095
0
    conf->f_vrfy      = f_vrfy;
4096
0
    conf->p_vrfy      = p_vrfy;
4097
0
}
4098
#endif /* MBEDTLS_X509_CRT_PARSE_C */
4099
4100
void mbedtls_ssl_conf_rng(mbedtls_ssl_config *conf,
4101
                          int (*f_rng)(void *, unsigned char *, size_t),
4102
                          void *p_rng)
4103
4.44k
{
4104
4.44k
    conf->f_rng      = f_rng;
4105
4.44k
    conf->p_rng      = p_rng;
4106
4.44k
}
4107
4108
void mbedtls_ssl_conf_dbg(mbedtls_ssl_config *conf,
4109
                          void (*f_dbg)(void *, int, const char *, int, const char *),
4110
                          void  *p_dbg)
4111
4.38k
{
4112
4.38k
    conf->f_dbg      = f_dbg;
4113
4.38k
    conf->p_dbg      = p_dbg;
4114
4.38k
}
4115
4116
void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl,
4117
                         void *p_bio,
4118
                         mbedtls_ssl_send_t *f_send,
4119
                         mbedtls_ssl_recv_t *f_recv,
4120
                         mbedtls_ssl_recv_timeout_t *f_recv_timeout)
4121
4.38k
{
4122
4.38k
    ssl->p_bio          = p_bio;
4123
4.38k
    ssl->f_send         = f_send;
4124
4.38k
    ssl->f_recv         = f_recv;
4125
4.38k
    ssl->f_recv_timeout = f_recv_timeout;
4126
4.38k
}
4127
4128
#if defined(MBEDTLS_SSL_PROTO_DTLS)
4129
void mbedtls_ssl_set_mtu(mbedtls_ssl_context *ssl, uint16_t mtu)
4130
0
{
4131
0
    ssl->mtu = mtu;
4132
0
}
4133
#endif
4134
4135
void mbedtls_ssl_conf_read_timeout(mbedtls_ssl_config *conf, uint32_t timeout)
4136
0
{
4137
0
    conf->read_timeout   = timeout;
4138
0
}
4139
4140
void mbedtls_ssl_set_timer_cb(mbedtls_ssl_context *ssl,
4141
                              void *p_timer,
4142
                              mbedtls_ssl_set_timer_t *f_set_timer,
4143
                              mbedtls_ssl_get_timer_t *f_get_timer)
4144
4.38k
{
4145
4.38k
    ssl->p_timer        = p_timer;
4146
4.38k
    ssl->f_set_timer    = f_set_timer;
4147
4.38k
    ssl->f_get_timer    = f_get_timer;
4148
4149
    /* Make sure we start with no timer running */
4150
4.38k
    mbedtls_ssl_set_timer(ssl, 0);
4151
4.38k
}
4152
4153
#if defined(MBEDTLS_SSL_SRV_C)
4154
void mbedtls_ssl_conf_session_cache(mbedtls_ssl_config *conf,
4155
                                    void *p_cache,
4156
                                    int (*f_get_cache)(void *, mbedtls_ssl_session *),
4157
                                    int (*f_set_cache)(void *, const mbedtls_ssl_session *))
4158
0
{
4159
0
    conf->p_cache = p_cache;
4160
0
    conf->f_get_cache = f_get_cache;
4161
0
    conf->f_set_cache = f_set_cache;
4162
0
}
4163
#endif /* MBEDTLS_SSL_SRV_C */
4164
4165
#if defined(MBEDTLS_SSL_CLI_C)
4166
int mbedtls_ssl_set_session(mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session)
4167
0
{
4168
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4169
4170
0
    if (ssl == NULL ||
4171
0
        session == NULL ||
4172
0
        ssl->session_negotiate == NULL ||
4173
0
        ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
4174
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4175
0
    }
4176
4177
0
    if ((ret = mbedtls_ssl_session_copy(ssl->session_negotiate,
4178
0
                                        session)) != 0) {
4179
0
        return ret;
4180
0
    }
4181
4182
0
    ssl->handshake->resume = 1;
4183
4184
0
    return 0;
4185
0
}
4186
#endif /* MBEDTLS_SSL_CLI_C */
4187
4188
void mbedtls_ssl_conf_ciphersuites(mbedtls_ssl_config *conf,
4189
                                   const int *ciphersuites)
4190
4.44k
{
4191
4.44k
    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] = ciphersuites;
4192
4.44k
    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] = ciphersuites;
4193
4.44k
    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] = ciphersuites;
4194
4.44k
    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] = ciphersuites;
4195
4.44k
}
4196
4197
void mbedtls_ssl_conf_ciphersuites_for_version(mbedtls_ssl_config *conf,
4198
                                               const int *ciphersuites,
4199
                                               int major, int minor)
4200
0
{
4201
0
    if (major != MBEDTLS_SSL_MAJOR_VERSION_3) {
4202
0
        return;
4203
0
    }
4204
4205
0
    if (minor < MBEDTLS_SSL_MINOR_VERSION_0 || minor > MBEDTLS_SSL_MINOR_VERSION_3) {
4206
0
        return;
4207
0
    }
4208
4209
0
    conf->ciphersuite_list[minor] = ciphersuites;
4210
0
}
4211
4212
#if defined(MBEDTLS_X509_CRT_PARSE_C)
4213
void mbedtls_ssl_conf_cert_profile(mbedtls_ssl_config *conf,
4214
                                   const mbedtls_x509_crt_profile *profile)
4215
0
{
4216
0
    conf->cert_profile = profile;
4217
0
}
4218
4219
/* Append a new keycert entry to a (possibly empty) list */
4220
MBEDTLS_CHECK_RETURN_CRITICAL
4221
static int ssl_append_key_cert(mbedtls_ssl_key_cert **head,
4222
                               mbedtls_x509_crt *cert,
4223
                               mbedtls_pk_context *key)
4224
0
{
4225
0
    mbedtls_ssl_key_cert *new_cert;
4226
4227
0
    new_cert = mbedtls_calloc(1, sizeof(mbedtls_ssl_key_cert));
4228
0
    if (new_cert == NULL) {
4229
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
4230
0
    }
4231
4232
0
    new_cert->cert = cert;
4233
0
    new_cert->key  = key;
4234
0
    new_cert->next = NULL;
4235
4236
    /* Update head is the list was null, else add to the end */
4237
0
    if (*head == NULL) {
4238
0
        *head = new_cert;
4239
0
    } else {
4240
0
        mbedtls_ssl_key_cert *cur = *head;
4241
0
        while (cur->next != NULL) {
4242
0
            cur = cur->next;
4243
0
        }
4244
0
        cur->next = new_cert;
4245
0
    }
4246
4247
0
    return 0;
4248
0
}
4249
4250
int mbedtls_ssl_conf_own_cert(mbedtls_ssl_config *conf,
4251
                              mbedtls_x509_crt *own_cert,
4252
                              mbedtls_pk_context *pk_key)
4253
0
{
4254
0
    return ssl_append_key_cert(&conf->key_cert, own_cert, pk_key);
4255
0
}
4256
4257
void mbedtls_ssl_conf_ca_chain(mbedtls_ssl_config *conf,
4258
                               mbedtls_x509_crt *ca_chain,
4259
                               mbedtls_x509_crl *ca_crl)
4260
0
{
4261
0
    conf->ca_chain   = ca_chain;
4262
0
    conf->ca_crl     = ca_crl;
4263
4264
#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
4265
    /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
4266
     * cannot be used together. */
4267
    conf->f_ca_cb = NULL;
4268
    conf->p_ca_cb = NULL;
4269
#endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
4270
0
}
4271
4272
#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
4273
void mbedtls_ssl_conf_ca_cb(mbedtls_ssl_config *conf,
4274
                            mbedtls_x509_crt_ca_cb_t f_ca_cb,
4275
                            void *p_ca_cb)
4276
{
4277
    conf->f_ca_cb = f_ca_cb;
4278
    conf->p_ca_cb = p_ca_cb;
4279
4280
    /* mbedtls_ssl_conf_ca_chain() and mbedtls_ssl_conf_ca_cb()
4281
     * cannot be used together. */
4282
    conf->ca_chain   = NULL;
4283
    conf->ca_crl     = NULL;
4284
}
4285
#endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
4286
#endif /* MBEDTLS_X509_CRT_PARSE_C */
4287
4288
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4289
int mbedtls_ssl_set_hs_own_cert(mbedtls_ssl_context *ssl,
4290
                                mbedtls_x509_crt *own_cert,
4291
                                mbedtls_pk_context *pk_key)
4292
{
4293
    return ssl_append_key_cert(&ssl->handshake->sni_key_cert,
4294
                               own_cert, pk_key);
4295
}
4296
4297
void mbedtls_ssl_set_hs_ca_chain(mbedtls_ssl_context *ssl,
4298
                                 mbedtls_x509_crt *ca_chain,
4299
                                 mbedtls_x509_crl *ca_crl)
4300
{
4301
    ssl->handshake->sni_ca_chain   = ca_chain;
4302
    ssl->handshake->sni_ca_crl     = ca_crl;
4303
}
4304
4305
void mbedtls_ssl_set_hs_authmode(mbedtls_ssl_context *ssl,
4306
                                 int authmode)
4307
{
4308
    ssl->handshake->sni_authmode = authmode;
4309
}
4310
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
4311
4312
#if defined(MBEDTLS_X509_CRT_PARSE_C)
4313
void mbedtls_ssl_set_verify(mbedtls_ssl_context *ssl,
4314
                            int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
4315
                            void *p_vrfy)
4316
0
{
4317
0
    ssl->f_vrfy = f_vrfy;
4318
0
    ssl->p_vrfy = p_vrfy;
4319
0
}
4320
#endif
4321
4322
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
4323
/*
4324
 * Set EC J-PAKE password for current handshake
4325
 */
4326
int mbedtls_ssl_set_hs_ecjpake_password(mbedtls_ssl_context *ssl,
4327
                                        const unsigned char *pw,
4328
                                        size_t pw_len)
4329
4.38k
{
4330
4.38k
    mbedtls_ecjpake_role role;
4331
4332
4.38k
    if (ssl->handshake == NULL || ssl->conf == NULL) {
4333
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4334
0
    }
4335
4336
4.38k
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
4337
4.38k
        role = MBEDTLS_ECJPAKE_SERVER;
4338
4.38k
    } else {
4339
0
        role = MBEDTLS_ECJPAKE_CLIENT;
4340
0
    }
4341
4342
4.38k
    return mbedtls_ecjpake_setup(&ssl->handshake->ecjpake_ctx,
4343
4.38k
                                 role,
4344
4.38k
                                 MBEDTLS_MD_SHA256,
4345
4.38k
                                 MBEDTLS_ECP_DP_SECP256R1,
4346
4.38k
                                 pw, pw_len);
4347
4.38k
}
4348
#endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
4349
4350
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
4351
4352
static void ssl_conf_remove_psk(mbedtls_ssl_config *conf)
4353
0
{
4354
    /* Remove reference to existing PSK, if any. */
4355
#if defined(MBEDTLS_USE_PSA_CRYPTO)
4356
    if (!mbedtls_svc_key_id_is_null(conf->psk_opaque)) {
4357
        /* The maintenance of the PSK key slot is the
4358
         * user's responsibility. */
4359
        conf->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
4360
    }
4361
    /* This and the following branch should never
4362
     * be taken simultaneously as we maintain the
4363
     * invariant that raw and opaque PSKs are never
4364
     * configured simultaneously. As a safeguard,
4365
     * though, `else` is omitted here. */
4366
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4367
0
    if (conf->psk != NULL) {
4368
0
        mbedtls_platform_zeroize(conf->psk, conf->psk_len);
4369
4370
0
        mbedtls_free(conf->psk);
4371
0
        conf->psk = NULL;
4372
0
        conf->psk_len = 0;
4373
0
    }
4374
4375
    /* Remove reference to PSK identity, if any. */
4376
0
    if (conf->psk_identity != NULL) {
4377
0
        mbedtls_free(conf->psk_identity);
4378
0
        conf->psk_identity = NULL;
4379
0
        conf->psk_identity_len = 0;
4380
0
    }
4381
0
}
4382
4383
/* This function assumes that PSK identity in the SSL config is unset.
4384
 * It checks that the provided identity is well-formed and attempts
4385
 * to make a copy of it in the SSL config.
4386
 * On failure, the PSK identity in the config remains unset. */
4387
MBEDTLS_CHECK_RETURN_CRITICAL
4388
static int ssl_conf_set_psk_identity(mbedtls_ssl_config *conf,
4389
                                     unsigned char const *psk_identity,
4390
                                     size_t psk_identity_len)
4391
0
{
4392
    /* Identity len will be encoded on two bytes */
4393
0
    if (psk_identity               == NULL ||
4394
0
        (psk_identity_len >> 16) != 0    ||
4395
0
        psk_identity_len > MBEDTLS_SSL_OUT_CONTENT_LEN) {
4396
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4397
0
    }
4398
4399
0
    conf->psk_identity = mbedtls_calloc(1, psk_identity_len);
4400
0
    if (conf->psk_identity == NULL) {
4401
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
4402
0
    }
4403
4404
0
    conf->psk_identity_len = psk_identity_len;
4405
0
    memcpy(conf->psk_identity, psk_identity, conf->psk_identity_len);
4406
4407
0
    return 0;
4408
0
}
4409
4410
int mbedtls_ssl_conf_psk(mbedtls_ssl_config *conf,
4411
                         const unsigned char *psk, size_t psk_len,
4412
                         const unsigned char *psk_identity, size_t psk_identity_len)
4413
0
{
4414
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4415
    /* Remove opaque/raw PSK + PSK Identity */
4416
0
    ssl_conf_remove_psk(conf);
4417
4418
    /* Check and set raw PSK */
4419
0
    if (psk == NULL) {
4420
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4421
0
    }
4422
0
    if (psk_len == 0) {
4423
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4424
0
    }
4425
0
    if (psk_len > MBEDTLS_PSK_MAX_LEN) {
4426
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4427
0
    }
4428
4429
0
    if ((conf->psk = mbedtls_calloc(1, psk_len)) == NULL) {
4430
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
4431
0
    }
4432
0
    conf->psk_len = psk_len;
4433
0
    memcpy(conf->psk, psk, conf->psk_len);
4434
4435
    /* Check and set PSK Identity */
4436
0
    ret = ssl_conf_set_psk_identity(conf, psk_identity, psk_identity_len);
4437
0
    if (ret != 0) {
4438
0
        ssl_conf_remove_psk(conf);
4439
0
    }
4440
4441
0
    return ret;
4442
0
}
4443
4444
static void ssl_remove_psk(mbedtls_ssl_context *ssl)
4445
0
{
4446
#if defined(MBEDTLS_USE_PSA_CRYPTO)
4447
    if (!mbedtls_svc_key_id_is_null(ssl->handshake->psk_opaque)) {
4448
        ssl->handshake->psk_opaque = MBEDTLS_SVC_KEY_ID_INIT;
4449
    } else
4450
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4451
0
    if (ssl->handshake->psk != NULL) {
4452
0
        mbedtls_platform_zeroize(ssl->handshake->psk,
4453
0
                                 ssl->handshake->psk_len);
4454
0
        mbedtls_free(ssl->handshake->psk);
4455
0
        ssl->handshake->psk_len = 0;
4456
0
    }
4457
0
}
4458
4459
int mbedtls_ssl_set_hs_psk(mbedtls_ssl_context *ssl,
4460
                           const unsigned char *psk, size_t psk_len)
4461
0
{
4462
0
    if (psk == NULL || ssl->handshake == NULL) {
4463
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4464
0
    }
4465
4466
0
    if (psk_len > MBEDTLS_PSK_MAX_LEN) {
4467
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4468
0
    }
4469
4470
0
    ssl_remove_psk(ssl);
4471
4472
0
    if ((ssl->handshake->psk = mbedtls_calloc(1, psk_len)) == NULL) {
4473
0
        return MBEDTLS_ERR_SSL_ALLOC_FAILED;
4474
0
    }
4475
4476
0
    ssl->handshake->psk_len = psk_len;
4477
0
    memcpy(ssl->handshake->psk, psk, ssl->handshake->psk_len);
4478
4479
0
    return 0;
4480
0
}
4481
4482
#if defined(MBEDTLS_USE_PSA_CRYPTO)
4483
int mbedtls_ssl_conf_psk_opaque(mbedtls_ssl_config *conf,
4484
                                psa_key_id_t psk,
4485
                                const unsigned char *psk_identity,
4486
                                size_t psk_identity_len)
4487
{
4488
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4489
    /* Clear opaque/raw PSK + PSK Identity, if present. */
4490
    ssl_conf_remove_psk(conf);
4491
4492
    /* Check and set opaque PSK */
4493
    if (mbedtls_svc_key_id_is_null(psk)) {
4494
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4495
    }
4496
    conf->psk_opaque = psk;
4497
4498
    /* Check and set PSK Identity */
4499
    ret = ssl_conf_set_psk_identity(conf, psk_identity,
4500
                                    psk_identity_len);
4501
    if (ret != 0) {
4502
        ssl_conf_remove_psk(conf);
4503
    }
4504
4505
    return ret;
4506
}
4507
4508
int mbedtls_ssl_set_hs_psk_opaque(mbedtls_ssl_context *ssl,
4509
                                  psa_key_id_t psk)
4510
{
4511
    if ((mbedtls_svc_key_id_is_null(psk)) ||
4512
        (ssl->handshake == NULL)) {
4513
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4514
    }
4515
4516
    ssl_remove_psk(ssl);
4517
    ssl->handshake->psk_opaque = psk;
4518
    return 0;
4519
}
4520
#endif /* MBEDTLS_USE_PSA_CRYPTO */
4521
4522
void mbedtls_ssl_conf_psk_cb(mbedtls_ssl_config *conf,
4523
                             int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
4524
                                          size_t),
4525
                             void *p_psk)
4526
0
{
4527
0
    conf->f_psk = f_psk;
4528
0
    conf->p_psk = p_psk;
4529
0
}
4530
#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */
4531
4532
#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
4533
4534
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
4535
int mbedtls_ssl_conf_dh_param(mbedtls_ssl_config *conf, const char *dhm_P, const char *dhm_G)
4536
{
4537
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4538
4539
    if ((ret = mbedtls_mpi_read_string(&conf->dhm_P, 16, dhm_P)) != 0 ||
4540
        (ret = mbedtls_mpi_read_string(&conf->dhm_G, 16, dhm_G)) != 0) {
4541
        mbedtls_mpi_free(&conf->dhm_P);
4542
        mbedtls_mpi_free(&conf->dhm_G);
4543
        return ret;
4544
    }
4545
4546
    return 0;
4547
}
4548
#endif /* MBEDTLS_DEPRECATED_REMOVED */
4549
4550
int mbedtls_ssl_conf_dh_param_bin(mbedtls_ssl_config *conf,
4551
                                  const unsigned char *dhm_P, size_t P_len,
4552
                                  const unsigned char *dhm_G, size_t G_len)
4553
{
4554
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4555
4556
    mbedtls_mpi_free(&conf->dhm_P);
4557
    mbedtls_mpi_free(&conf->dhm_G);
4558
4559
    if ((ret = mbedtls_mpi_read_binary(&conf->dhm_P, dhm_P, P_len)) != 0 ||
4560
        (ret = mbedtls_mpi_read_binary(&conf->dhm_G, dhm_G, G_len)) != 0) {
4561
        mbedtls_mpi_free(&conf->dhm_P);
4562
        mbedtls_mpi_free(&conf->dhm_G);
4563
        return ret;
4564
    }
4565
4566
    return 0;
4567
}
4568
4569
int mbedtls_ssl_conf_dh_param_ctx(mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx)
4570
{
4571
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
4572
4573
    mbedtls_mpi_free(&conf->dhm_P);
4574
    mbedtls_mpi_free(&conf->dhm_G);
4575
4576
    if ((ret = mbedtls_mpi_copy(&conf->dhm_P, &dhm_ctx->P)) != 0 ||
4577
        (ret = mbedtls_mpi_copy(&conf->dhm_G, &dhm_ctx->G)) != 0) {
4578
        mbedtls_mpi_free(&conf->dhm_P);
4579
        mbedtls_mpi_free(&conf->dhm_G);
4580
        return ret;
4581
    }
4582
4583
    return 0;
4584
}
4585
#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_SRV_C */
4586
4587
#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
4588
/*
4589
 * Set the minimum length for Diffie-Hellman parameters
4590
 */
4591
void mbedtls_ssl_conf_dhm_min_bitlen(mbedtls_ssl_config *conf,
4592
                                     unsigned int bitlen)
4593
{
4594
    conf->dhm_min_bitlen = bitlen;
4595
}
4596
#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
4597
4598
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
4599
/*
4600
 * Set allowed/preferred hashes for handshake signatures
4601
 */
4602
void mbedtls_ssl_conf_sig_hashes(mbedtls_ssl_config *conf,
4603
                                 const int *hashes)
4604
4.38k
{
4605
4.38k
    conf->sig_hashes = hashes;
4606
4.38k
}
4607
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
4608
4609
#if defined(MBEDTLS_ECP_C)
4610
/*
4611
 * Set the allowed elliptic curves
4612
 */
4613
void mbedtls_ssl_conf_curves(mbedtls_ssl_config *conf,
4614
                             const mbedtls_ecp_group_id *curve_list)
4615
4.38k
{
4616
4.38k
    conf->curve_list = curve_list;
4617
4.38k
}
4618
#endif /* MBEDTLS_ECP_C */
4619
4620
#if defined(MBEDTLS_X509_CRT_PARSE_C)
4621
int mbedtls_ssl_set_hostname(mbedtls_ssl_context *ssl, const char *hostname)
4622
0
{
4623
    /* Initialize to suppress unnecessary compiler warning */
4624
0
    size_t hostname_len = 0;
4625
4626
    /* Check if new hostname is valid before
4627
     * making any change to current one */
4628
0
    if (hostname != NULL) {
4629
0
        hostname_len = strlen(hostname);
4630
4631
0
        if (hostname_len > MBEDTLS_SSL_MAX_HOST_NAME_LEN) {
4632
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4633
0
        }
4634
0
    }
4635
4636
    /* Now it's clear that we will overwrite the old hostname,
4637
     * so we can free it safely */
4638
4639
0
    if (ssl->hostname != NULL) {
4640
0
        mbedtls_platform_zeroize(ssl->hostname, strlen(ssl->hostname));
4641
0
        mbedtls_free(ssl->hostname);
4642
0
    }
4643
4644
    /* Passing NULL as hostname shall clear the old one */
4645
4646
0
    if (hostname == NULL) {
4647
0
        ssl->hostname = NULL;
4648
0
    } else {
4649
0
        ssl->hostname = mbedtls_calloc(1, hostname_len + 1);
4650
0
        if (ssl->hostname == NULL) {
4651
0
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
4652
0
        }
4653
4654
0
        memcpy(ssl->hostname, hostname, hostname_len);
4655
4656
0
        ssl->hostname[hostname_len] = '\0';
4657
0
    }
4658
4659
0
    return 0;
4660
0
}
4661
#endif /* MBEDTLS_X509_CRT_PARSE_C */
4662
4663
#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
4664
void mbedtls_ssl_conf_sni(mbedtls_ssl_config *conf,
4665
                          int (*f_sni)(void *, mbedtls_ssl_context *,
4666
                                       const unsigned char *, size_t),
4667
                          void *p_sni)
4668
{
4669
    conf->f_sni = f_sni;
4670
    conf->p_sni = p_sni;
4671
}
4672
#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
4673
4674
#if defined(MBEDTLS_SSL_ALPN)
4675
int mbedtls_ssl_conf_alpn_protocols(mbedtls_ssl_config *conf, const char **protos)
4676
{
4677
    size_t cur_len, tot_len;
4678
    const char **p;
4679
4680
    /*
4681
     * RFC 7301 3.1: "Empty strings MUST NOT be included and byte strings
4682
     * MUST NOT be truncated."
4683
     * We check lengths now rather than later.
4684
     */
4685
    tot_len = 0;
4686
    for (p = protos; *p != NULL; p++) {
4687
        cur_len = strlen(*p);
4688
        tot_len += cur_len;
4689
4690
        if ((cur_len == 0) ||
4691
            (cur_len > MBEDTLS_SSL_MAX_ALPN_NAME_LEN) ||
4692
            (tot_len > MBEDTLS_SSL_MAX_ALPN_LIST_LEN)) {
4693
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4694
        }
4695
    }
4696
4697
    conf->alpn_list = protos;
4698
4699
    return 0;
4700
}
4701
4702
const char *mbedtls_ssl_get_alpn_protocol(const mbedtls_ssl_context *ssl)
4703
{
4704
    return ssl->alpn_chosen;
4705
}
4706
#endif /* MBEDTLS_SSL_ALPN */
4707
4708
#if defined(MBEDTLS_SSL_DTLS_SRTP)
4709
void mbedtls_ssl_conf_srtp_mki_value_supported(mbedtls_ssl_config *conf,
4710
                                               int support_mki_value)
4711
{
4712
    conf->dtls_srtp_mki_support = support_mki_value;
4713
}
4714
4715
int mbedtls_ssl_dtls_srtp_set_mki_value(mbedtls_ssl_context *ssl,
4716
                                        unsigned char *mki_value,
4717
                                        uint16_t mki_len)
4718
{
4719
    if (mki_len > MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH) {
4720
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4721
    }
4722
4723
    if (ssl->conf->dtls_srtp_mki_support == MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED) {
4724
        return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
4725
    }
4726
4727
    memcpy(ssl->dtls_srtp_info.mki_value, mki_value, mki_len);
4728
    ssl->dtls_srtp_info.mki_len = mki_len;
4729
    return 0;
4730
}
4731
4732
int mbedtls_ssl_conf_dtls_srtp_protection_profiles(mbedtls_ssl_config *conf,
4733
                                                   const mbedtls_ssl_srtp_profile *profiles)
4734
{
4735
    const mbedtls_ssl_srtp_profile *p;
4736
    size_t list_size = 0;
4737
4738
    /* check the profiles list: all entry must be valid,
4739
     * its size cannot be more than the total number of supported profiles, currently 4 */
4740
    for (p = profiles; *p != MBEDTLS_TLS_SRTP_UNSET &&
4741
         list_size <= MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH;
4742
         p++) {
4743
        if (mbedtls_ssl_check_srtp_profile_value(*p) != MBEDTLS_TLS_SRTP_UNSET) {
4744
            list_size++;
4745
        } else {
4746
            /* unsupported value, stop parsing and set the size to an error value */
4747
            list_size = MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH + 1;
4748
        }
4749
    }
4750
4751
    if (list_size > MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH) {
4752
        conf->dtls_srtp_profile_list = NULL;
4753
        conf->dtls_srtp_profile_list_len = 0;
4754
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4755
    }
4756
4757
    conf->dtls_srtp_profile_list = profiles;
4758
    conf->dtls_srtp_profile_list_len = list_size;
4759
4760
    return 0;
4761
}
4762
4763
void mbedtls_ssl_get_dtls_srtp_negotiation_result(const mbedtls_ssl_context *ssl,
4764
                                                  mbedtls_dtls_srtp_info *dtls_srtp_info)
4765
{
4766
    dtls_srtp_info->chosen_dtls_srtp_profile = ssl->dtls_srtp_info.chosen_dtls_srtp_profile;
4767
    /* do not copy the mki value if there is no chosen profile */
4768
    if (dtls_srtp_info->chosen_dtls_srtp_profile == MBEDTLS_TLS_SRTP_UNSET) {
4769
        dtls_srtp_info->mki_len = 0;
4770
    } else {
4771
        dtls_srtp_info->mki_len = ssl->dtls_srtp_info.mki_len;
4772
        memcpy(dtls_srtp_info->mki_value, ssl->dtls_srtp_info.mki_value,
4773
               ssl->dtls_srtp_info.mki_len);
4774
    }
4775
}
4776
#endif /* MBEDTLS_SSL_DTLS_SRTP */
4777
4778
void mbedtls_ssl_conf_max_version(mbedtls_ssl_config *conf, int major, int minor)
4779
4.44k
{
4780
4.44k
    conf->max_major_ver = major;
4781
4.44k
    conf->max_minor_ver = minor;
4782
4.44k
}
4783
4784
void mbedtls_ssl_conf_min_version(mbedtls_ssl_config *conf, int major, int minor)
4785
4.44k
{
4786
4.44k
    conf->min_major_ver = major;
4787
4.44k
    conf->min_minor_ver = minor;
4788
4.44k
}
4789
4790
#if defined(MBEDTLS_SSL_FALLBACK_SCSV) && defined(MBEDTLS_SSL_CLI_C)
4791
void mbedtls_ssl_conf_fallback(mbedtls_ssl_config *conf, char fallback)
4792
{
4793
    conf->fallback = fallback;
4794
}
4795
#endif
4796
4797
#if defined(MBEDTLS_SSL_SRV_C)
4798
void mbedtls_ssl_conf_cert_req_ca_list(mbedtls_ssl_config *conf,
4799
                                       char cert_req_ca_list)
4800
0
{
4801
0
    conf->cert_req_ca_list = cert_req_ca_list;
4802
0
}
4803
#endif
4804
4805
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
4806
void mbedtls_ssl_conf_encrypt_then_mac(mbedtls_ssl_config *conf, char etm)
4807
{
4808
    conf->encrypt_then_mac = etm;
4809
}
4810
#endif
4811
4812
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
4813
void mbedtls_ssl_conf_extended_master_secret(mbedtls_ssl_config *conf, char ems)
4814
{
4815
    conf->extended_ms = ems;
4816
}
4817
#endif
4818
4819
#if defined(MBEDTLS_ARC4_C)
4820
void mbedtls_ssl_conf_arc4_support(mbedtls_ssl_config *conf, char arc4)
4821
{
4822
    conf->arc4_disabled = arc4;
4823
}
4824
#endif
4825
4826
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
4827
int mbedtls_ssl_conf_max_frag_len(mbedtls_ssl_config *conf, unsigned char mfl_code)
4828
0
{
4829
0
    if (mfl_code >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ||
4830
0
        ssl_mfl_code_to_length(mfl_code) > MBEDTLS_TLS_EXT_ADV_CONTENT_LEN) {
4831
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
4832
0
    }
4833
4834
0
    conf->mfl_code = mfl_code;
4835
4836
0
    return 0;
4837
0
}
4838
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
4839
4840
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
4841
void mbedtls_ssl_conf_truncated_hmac(mbedtls_ssl_config *conf, int truncate)
4842
{
4843
    conf->trunc_hmac = truncate;
4844
}
4845
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
4846
4847
#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
4848
void mbedtls_ssl_conf_cbc_record_splitting(mbedtls_ssl_config *conf, char split)
4849
{
4850
    conf->cbc_record_splitting = split;
4851
}
4852
#endif
4853
4854
void mbedtls_ssl_conf_legacy_renegotiation(mbedtls_ssl_config *conf, int allow_legacy)
4855
0
{
4856
0
    conf->allow_legacy_renegotiation = allow_legacy;
4857
0
}
4858
4859
#if defined(MBEDTLS_SSL_RENEGOTIATION)
4860
void mbedtls_ssl_conf_renegotiation(mbedtls_ssl_config *conf, int renegotiation)
4861
{
4862
    conf->disable_renegotiation = renegotiation;
4863
}
4864
4865
void mbedtls_ssl_conf_renegotiation_enforced(mbedtls_ssl_config *conf, int max_records)
4866
{
4867
    conf->renego_max_records = max_records;
4868
}
4869
4870
void mbedtls_ssl_conf_renegotiation_period(mbedtls_ssl_config *conf,
4871
                                           const unsigned char period[8])
4872
{
4873
    memcpy(conf->renego_period, period, 8);
4874
}
4875
#endif /* MBEDTLS_SSL_RENEGOTIATION */
4876
4877
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
4878
#if defined(MBEDTLS_SSL_CLI_C)
4879
void mbedtls_ssl_conf_session_tickets(mbedtls_ssl_config *conf, int use_tickets)
4880
{
4881
    conf->session_tickets = use_tickets;
4882
}
4883
#endif
4884
4885
#if defined(MBEDTLS_SSL_SRV_C)
4886
void mbedtls_ssl_conf_session_tickets_cb(mbedtls_ssl_config *conf,
4887
                                         mbedtls_ssl_ticket_write_t *f_ticket_write,
4888
                                         mbedtls_ssl_ticket_parse_t *f_ticket_parse,
4889
                                         void *p_ticket)
4890
{
4891
    conf->f_ticket_write = f_ticket_write;
4892
    conf->f_ticket_parse = f_ticket_parse;
4893
    conf->p_ticket       = p_ticket;
4894
}
4895
#endif
4896
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
4897
4898
#if defined(MBEDTLS_SSL_EXPORT_KEYS)
4899
void mbedtls_ssl_conf_export_keys_cb(mbedtls_ssl_config *conf,
4900
                                     mbedtls_ssl_export_keys_t *f_export_keys,
4901
                                     void *p_export_keys)
4902
4.38k
{
4903
4.38k
    conf->f_export_keys = f_export_keys;
4904
4.38k
    conf->p_export_keys = p_export_keys;
4905
4.38k
}
4906
4907
void mbedtls_ssl_conf_export_keys_ext_cb(mbedtls_ssl_config *conf,
4908
                                         mbedtls_ssl_export_keys_ext_t *f_export_keys_ext,
4909
                                         void *p_export_keys)
4910
0
{
4911
0
    conf->f_export_keys_ext = f_export_keys_ext;
4912
0
    conf->p_export_keys = p_export_keys;
4913
0
}
4914
#endif
4915
4916
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
4917
void mbedtls_ssl_conf_async_private_cb(
4918
    mbedtls_ssl_config *conf,
4919
    mbedtls_ssl_async_sign_t *f_async_sign,
4920
    mbedtls_ssl_async_decrypt_t *f_async_decrypt,
4921
    mbedtls_ssl_async_resume_t *f_async_resume,
4922
    mbedtls_ssl_async_cancel_t *f_async_cancel,
4923
    void *async_config_data)
4924
{
4925
    conf->f_async_sign_start = f_async_sign;
4926
    conf->f_async_decrypt_start = f_async_decrypt;
4927
    conf->f_async_resume = f_async_resume;
4928
    conf->f_async_cancel = f_async_cancel;
4929
    conf->p_async_config_data = async_config_data;
4930
}
4931
4932
void *mbedtls_ssl_conf_get_async_config_data(const mbedtls_ssl_config *conf)
4933
{
4934
    return conf->p_async_config_data;
4935
}
4936
4937
void *mbedtls_ssl_get_async_operation_data(const mbedtls_ssl_context *ssl)
4938
{
4939
    if (ssl->handshake == NULL) {
4940
        return NULL;
4941
    } else {
4942
        return ssl->handshake->user_async_ctx;
4943
    }
4944
}
4945
4946
void mbedtls_ssl_set_async_operation_data(mbedtls_ssl_context *ssl,
4947
                                          void *ctx)
4948
{
4949
    if (ssl->handshake != NULL) {
4950
        ssl->handshake->user_async_ctx = ctx;
4951
    }
4952
}
4953
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
4954
4955
/*
4956
 * SSL get accessors
4957
 */
4958
uint32_t mbedtls_ssl_get_verify_result(const mbedtls_ssl_context *ssl)
4959
0
{
4960
0
    if (ssl->session != NULL) {
4961
0
        return ssl->session->verify_result;
4962
0
    }
4963
4964
0
    if (ssl->session_negotiate != NULL) {
4965
0
        return ssl->session_negotiate->verify_result;
4966
0
    }
4967
4968
0
    return 0xFFFFFFFF;
4969
0
}
4970
4971
const char *mbedtls_ssl_get_ciphersuite(const mbedtls_ssl_context *ssl)
4972
0
{
4973
0
    if (ssl == NULL || ssl->session == NULL) {
4974
0
        return NULL;
4975
0
    }
4976
4977
0
    return mbedtls_ssl_get_ciphersuite_name(ssl->session->ciphersuite);
4978
0
}
4979
4980
const char *mbedtls_ssl_get_version(const mbedtls_ssl_context *ssl)
4981
0
{
4982
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
4983
0
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
4984
0
        switch (ssl->minor_ver) {
4985
0
            case MBEDTLS_SSL_MINOR_VERSION_2:
4986
0
                return "DTLSv1.0";
4987
4988
0
            case MBEDTLS_SSL_MINOR_VERSION_3:
4989
0
                return "DTLSv1.2";
4990
4991
0
            default:
4992
0
                return "unknown (DTLS)";
4993
0
        }
4994
0
    }
4995
0
#endif
4996
4997
0
    switch (ssl->minor_ver) {
4998
0
        case MBEDTLS_SSL_MINOR_VERSION_0:
4999
0
            return "SSLv3.0";
5000
5001
0
        case MBEDTLS_SSL_MINOR_VERSION_1:
5002
0
            return "TLSv1.0";
5003
5004
0
        case MBEDTLS_SSL_MINOR_VERSION_2:
5005
0
            return "TLSv1.1";
5006
5007
0
        case MBEDTLS_SSL_MINOR_VERSION_3:
5008
0
            return "TLSv1.2";
5009
5010
0
        default:
5011
0
            return "unknown";
5012
0
    }
5013
0
}
5014
5015
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5016
size_t mbedtls_ssl_get_input_max_frag_len(const mbedtls_ssl_context *ssl)
5017
0
{
5018
0
    size_t max_len = MBEDTLS_SSL_MAX_CONTENT_LEN;
5019
0
    size_t read_mfl;
5020
5021
    /* Use the configured MFL for the client if we're past SERVER_HELLO_DONE */
5022
0
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
5023
0
        ssl->state >= MBEDTLS_SSL_SERVER_HELLO_DONE) {
5024
0
        return ssl_mfl_code_to_length(ssl->conf->mfl_code);
5025
0
    }
5026
5027
    /* Check if a smaller max length was negotiated */
5028
0
    if (ssl->session_out != NULL) {
5029
0
        read_mfl = ssl_mfl_code_to_length(ssl->session_out->mfl_code);
5030
0
        if (read_mfl < max_len) {
5031
0
            max_len = read_mfl;
5032
0
        }
5033
0
    }
5034
5035
    // During a handshake, use the value being negotiated
5036
0
    if (ssl->session_negotiate != NULL) {
5037
0
        read_mfl = ssl_mfl_code_to_length(ssl->session_negotiate->mfl_code);
5038
0
        if (read_mfl < max_len) {
5039
0
            max_len = read_mfl;
5040
0
        }
5041
0
    }
5042
5043
0
    return max_len;
5044
0
}
5045
5046
size_t mbedtls_ssl_get_output_max_frag_len(const mbedtls_ssl_context *ssl)
5047
0
{
5048
0
    size_t max_len;
5049
5050
    /*
5051
     * Assume mfl_code is correct since it was checked when set
5052
     */
5053
0
    max_len = ssl_mfl_code_to_length(ssl->conf->mfl_code);
5054
5055
    /* Check if a smaller max length was negotiated */
5056
0
    if (ssl->session_out != NULL &&
5057
0
        ssl_mfl_code_to_length(ssl->session_out->mfl_code) < max_len) {
5058
0
        max_len = ssl_mfl_code_to_length(ssl->session_out->mfl_code);
5059
0
    }
5060
5061
    /* During a handshake, use the value being negotiated */
5062
0
    if (ssl->session_negotiate != NULL &&
5063
0
        ssl_mfl_code_to_length(ssl->session_negotiate->mfl_code) < max_len) {
5064
0
        max_len = ssl_mfl_code_to_length(ssl->session_negotiate->mfl_code);
5065
0
    }
5066
5067
0
    return max_len;
5068
0
}
5069
5070
#if !defined(MBEDTLS_DEPRECATED_REMOVED)
5071
size_t mbedtls_ssl_get_max_frag_len(const mbedtls_ssl_context *ssl)
5072
0
{
5073
0
    return mbedtls_ssl_get_output_max_frag_len(ssl);
5074
0
}
5075
#endif /* !MBEDTLS_DEPRECATED_REMOVED */
5076
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
5077
5078
#if defined(MBEDTLS_SSL_PROTO_DTLS)
5079
size_t mbedtls_ssl_get_current_mtu(const mbedtls_ssl_context *ssl)
5080
4.33k
{
5081
    /* Return unlimited mtu for client hello messages to avoid fragmentation. */
5082
4.33k
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT &&
5083
4.33k
        (ssl->state == MBEDTLS_SSL_CLIENT_HELLO ||
5084
0
         ssl->state == MBEDTLS_SSL_SERVER_HELLO)) {
5085
0
        return 0;
5086
0
    }
5087
5088
4.33k
    if (ssl->handshake == NULL || ssl->handshake->mtu == 0) {
5089
4.33k
        return ssl->mtu;
5090
4.33k
    }
5091
5092
0
    if (ssl->mtu == 0) {
5093
0
        return ssl->handshake->mtu;
5094
0
    }
5095
5096
0
    return ssl->mtu < ssl->handshake->mtu ?
5097
0
           ssl->mtu : ssl->handshake->mtu;
5098
0
}
5099
#endif /* MBEDTLS_SSL_PROTO_DTLS */
5100
5101
int mbedtls_ssl_get_max_out_record_payload(const mbedtls_ssl_context *ssl)
5102
0
{
5103
0
    size_t max_len = MBEDTLS_SSL_OUT_CONTENT_LEN;
5104
5105
#if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) && \
5106
    !defined(MBEDTLS_SSL_PROTO_DTLS)
5107
    (void) ssl;
5108
#endif
5109
5110
0
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5111
0
    const size_t mfl = mbedtls_ssl_get_output_max_frag_len(ssl);
5112
5113
0
    if (max_len > mfl) {
5114
0
        max_len = mfl;
5115
0
    }
5116
0
#endif
5117
5118
0
#if defined(MBEDTLS_SSL_PROTO_DTLS)
5119
0
    if (mbedtls_ssl_get_current_mtu(ssl) != 0) {
5120
0
        const size_t mtu = mbedtls_ssl_get_current_mtu(ssl);
5121
0
        const int ret = mbedtls_ssl_get_record_expansion(ssl);
5122
0
        const size_t overhead = (size_t) ret;
5123
5124
0
        if (ret < 0) {
5125
0
            return ret;
5126
0
        }
5127
5128
0
        if (mtu <= overhead) {
5129
0
            MBEDTLS_SSL_DEBUG_MSG(1, ("MTU too low for record expansion"));
5130
0
            return MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
5131
0
        }
5132
5133
0
        if (max_len > mtu - overhead) {
5134
0
            max_len = mtu - overhead;
5135
0
        }
5136
0
    }
5137
0
#endif /* MBEDTLS_SSL_PROTO_DTLS */
5138
5139
#if !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) &&        \
5140
    !defined(MBEDTLS_SSL_PROTO_DTLS)
5141
    ((void) ssl);
5142
#endif
5143
5144
0
    return (int) max_len;
5145
0
}
5146
5147
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5148
const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert(const mbedtls_ssl_context *ssl)
5149
0
{
5150
0
    if (ssl == NULL || ssl->session == NULL) {
5151
0
        return NULL;
5152
0
    }
5153
5154
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5155
    return ssl->session->peer_cert;
5156
#else
5157
0
    return NULL;
5158
0
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5159
0
}
5160
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5161
5162
#if defined(MBEDTLS_SSL_CLI_C)
5163
int mbedtls_ssl_get_session(const mbedtls_ssl_context *ssl,
5164
                            mbedtls_ssl_session *dst)
5165
0
{
5166
0
    if (ssl == NULL ||
5167
0
        dst == NULL ||
5168
0