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
        ssl->session == NULL ||
5169
0
        ssl->conf->endpoint != MBEDTLS_SSL_IS_CLIENT) {
5170
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5171
0
    }
5172
5173
0
    return mbedtls_ssl_session_copy(dst, ssl->session);
5174
0
}
5175
#endif /* MBEDTLS_SSL_CLI_C */
5176
5177
const mbedtls_ssl_session *mbedtls_ssl_get_session_pointer(const mbedtls_ssl_context *ssl)
5178
0
{
5179
0
    if (ssl == NULL) {
5180
0
        return NULL;
5181
0
    }
5182
5183
0
    return ssl->session;
5184
0
}
5185
5186
/*
5187
 * Define ticket header determining Mbed TLS version
5188
 * and structure of the ticket.
5189
 */
5190
5191
/*
5192
 * Define bitflag determining compile-time settings influencing
5193
 * structure of serialized SSL sessions.
5194
 */
5195
5196
#if defined(MBEDTLS_HAVE_TIME)
5197
#define SSL_SERIALIZED_SESSION_CONFIG_TIME 1
5198
#else
5199
#define SSL_SERIALIZED_SESSION_CONFIG_TIME 0
5200
#endif /* MBEDTLS_HAVE_TIME */
5201
5202
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5203
#define SSL_SERIALIZED_SESSION_CONFIG_CRT 1
5204
#else
5205
#define SSL_SERIALIZED_SESSION_CONFIG_CRT 0
5206
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5207
5208
#if defined(MBEDTLS_SSL_CLI_C) && defined(MBEDTLS_SSL_SESSION_TICKETS)
5209
#define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 1
5210
#else
5211
#define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET 0
5212
#endif /* MBEDTLS_SSL_CLI_C && MBEDTLS_SSL_SESSION_TICKETS */
5213
5214
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5215
#define SSL_SERIALIZED_SESSION_CONFIG_MFL 1
5216
#else
5217
#define SSL_SERIALIZED_SESSION_CONFIG_MFL 0
5218
#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
5219
5220
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5221
#define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 1
5222
#else
5223
#define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC 0
5224
#endif /* MBEDTLS_SSL_TRUNCATED_HMAC */
5225
5226
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5227
#define SSL_SERIALIZED_SESSION_CONFIG_ETM 1
5228
#else
5229
#define SSL_SERIALIZED_SESSION_CONFIG_ETM 0
5230
#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
5231
5232
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
5233
#define SSL_SERIALIZED_SESSION_CONFIG_TICKET 1
5234
#else
5235
#define SSL_SERIALIZED_SESSION_CONFIG_TICKET 0
5236
#endif /* MBEDTLS_SSL_SESSION_TICKETS */
5237
5238
#define SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT          0
5239
#define SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT           1
5240
#define SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT 2
5241
#define SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT           3
5242
#define SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT    4
5243
#define SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT           5
5244
#define SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT        6
5245
5246
#define SSL_SERIALIZED_SESSION_CONFIG_BITFLAG                           \
5247
    ((uint16_t) (                                                      \
5248
         (SSL_SERIALIZED_SESSION_CONFIG_TIME << SSL_SERIALIZED_SESSION_CONFIG_TIME_BIT) | \
5249
         (SSL_SERIALIZED_SESSION_CONFIG_CRT << SSL_SERIALIZED_SESSION_CONFIG_CRT_BIT) | \
5250
         (SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET << \
5251
             SSL_SERIALIZED_SESSION_CONFIG_CLIENT_TICKET_BIT) | \
5252
         (SSL_SERIALIZED_SESSION_CONFIG_MFL << SSL_SERIALIZED_SESSION_CONFIG_MFL_BIT) | \
5253
         (SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC << \
5254
             SSL_SERIALIZED_SESSION_CONFIG_TRUNC_HMAC_BIT) | \
5255
         (SSL_SERIALIZED_SESSION_CONFIG_ETM << SSL_SERIALIZED_SESSION_CONFIG_ETM_BIT) | \
5256
         (SSL_SERIALIZED_SESSION_CONFIG_TICKET << SSL_SERIALIZED_SESSION_CONFIG_TICKET_BIT)))
5257
5258
static unsigned char ssl_serialized_session_header[] = {
5259
    MBEDTLS_VERSION_MAJOR,
5260
    MBEDTLS_VERSION_MINOR,
5261
    MBEDTLS_VERSION_PATCH,
5262
    MBEDTLS_BYTE_1(SSL_SERIALIZED_SESSION_CONFIG_BITFLAG),
5263
    MBEDTLS_BYTE_0(SSL_SERIALIZED_SESSION_CONFIG_BITFLAG),
5264
};
5265
5266
/*
5267
 * Serialize a session in the following format:
5268
 * (in the presentation language of TLS, RFC 8446 section 3)
5269
 *
5270
 *  opaque mbedtls_version[3];   // major, minor, patch
5271
 *  opaque session_format[2];    // version-specific 16-bit field determining
5272
 *                               // the format of the remaining
5273
 *                               // serialized data.
5274
 *
5275
 *  Note: When updating the format, remember to keep
5276
 *        these version+format bytes.
5277
 *
5278
 *                               // In this version, `session_format` determines
5279
 *                               // the setting of those compile-time
5280
 *                               // configuration options which influence
5281
 *                               // the structure of mbedtls_ssl_session.
5282
 *  uint64 start_time;
5283
 *  uint8 ciphersuite[2];        // defined by the standard
5284
 *  uint8 compression;           // 0 or 1
5285
 *  uint8 session_id_len;        // at most 32
5286
 *  opaque session_id[32];
5287
 *  opaque master[48];           // fixed length in the standard
5288
 *  uint32 verify_result;
5289
 *  opaque peer_cert<0..2^24-1>; // length 0 means no peer cert
5290
 *  opaque ticket<0..2^24-1>;    // length 0 means no ticket
5291
 *  uint32 ticket_lifetime;
5292
 *  uint8 mfl_code;              // up to 255 according to standard
5293
 *  uint8 trunc_hmac;            // 0 or 1
5294
 *  uint8 encrypt_then_mac;      // 0 or 1
5295
 *
5296
 * The order is the same as in the definition of the structure, except
5297
 * verify_result is put before peer_cert so that all mandatory fields come
5298
 * together in one block.
5299
 */
5300
MBEDTLS_CHECK_RETURN_CRITICAL
5301
static int ssl_session_save(const mbedtls_ssl_session *session,
5302
                            unsigned char omit_header,
5303
                            unsigned char *buf,
5304
                            size_t buf_len,
5305
                            size_t *olen)
5306
0
{
5307
0
    unsigned char *p = buf;
5308
0
    size_t used = 0;
5309
#if defined(MBEDTLS_HAVE_TIME)
5310
    uint64_t start;
5311
#endif
5312
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5313
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5314
    size_t cert_len;
5315
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5316
0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5317
5318
5319
0
    if (!omit_header) {
5320
        /*
5321
         * Add version identifier
5322
         */
5323
5324
0
        used += sizeof(ssl_serialized_session_header);
5325
5326
0
        if (used <= buf_len) {
5327
0
            memcpy(p, ssl_serialized_session_header,
5328
0
                   sizeof(ssl_serialized_session_header));
5329
0
            p += sizeof(ssl_serialized_session_header);
5330
0
        }
5331
0
    }
5332
5333
    /*
5334
     * Time
5335
     */
5336
#if defined(MBEDTLS_HAVE_TIME)
5337
    used += 8;
5338
5339
    if (used <= buf_len) {
5340
        start = (uint64_t) session->start;
5341
5342
        MBEDTLS_PUT_UINT64_BE(start, p, 0);
5343
        p += 8;
5344
    }
5345
#endif /* MBEDTLS_HAVE_TIME */
5346
5347
    /*
5348
     * Basic mandatory fields
5349
     */
5350
0
    used += 2   /* ciphersuite */
5351
0
            + 1 /* compression */
5352
0
            + 1 /* id_len */
5353
0
            + sizeof(session->id)
5354
0
            + sizeof(session->master)
5355
0
            + 4; /* verify_result */
5356
5357
0
    if (used <= buf_len) {
5358
0
        MBEDTLS_PUT_UINT16_BE(session->ciphersuite, p, 0);
5359
0
        p += 2;
5360
5361
0
        *p++ = MBEDTLS_BYTE_0(session->compression);
5362
5363
0
        *p++ = MBEDTLS_BYTE_0(session->id_len);
5364
0
        memcpy(p, session->id, 32);
5365
0
        p += 32;
5366
5367
0
        memcpy(p, session->master, 48);
5368
0
        p += 48;
5369
5370
0
        MBEDTLS_PUT_UINT32_BE(session->verify_result, p, 0);
5371
0
        p += 4;
5372
0
    }
5373
5374
    /*
5375
     * Peer's end-entity certificate
5376
     */
5377
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5378
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5379
    if (session->peer_cert == NULL) {
5380
        cert_len = 0;
5381
    } else {
5382
        cert_len = session->peer_cert->raw.len;
5383
    }
5384
5385
    used += 3 + cert_len;
5386
5387
    if (used <= buf_len) {
5388
        *p++ = MBEDTLS_BYTE_2(cert_len);
5389
        *p++ = MBEDTLS_BYTE_1(cert_len);
5390
        *p++ = MBEDTLS_BYTE_0(cert_len);
5391
5392
        if (session->peer_cert != NULL) {
5393
            memcpy(p, session->peer_cert->raw.p, cert_len);
5394
            p += cert_len;
5395
        }
5396
    }
5397
#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5398
0
    if (session->peer_cert_digest != NULL) {
5399
0
        used += 1 /* type */ + 1 /* length */ + session->peer_cert_digest_len;
5400
0
        if (used <= buf_len) {
5401
0
            *p++ = (unsigned char) session->peer_cert_digest_type;
5402
0
            *p++ = (unsigned char) session->peer_cert_digest_len;
5403
0
            memcpy(p, session->peer_cert_digest,
5404
0
                   session->peer_cert_digest_len);
5405
0
            p += session->peer_cert_digest_len;
5406
0
        }
5407
0
    } else {
5408
0
        used += 2;
5409
0
        if (used <= buf_len) {
5410
0
            *p++ = (unsigned char) MBEDTLS_MD_NONE;
5411
0
            *p++ = 0;
5412
0
        }
5413
0
    }
5414
0
#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5415
0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5416
5417
    /*
5418
     * Session ticket if any, plus associated data
5419
     */
5420
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5421
    used += 3 + session->ticket_len + 4; /* len + ticket + lifetime */
5422
5423
    if (used <= buf_len) {
5424
        *p++ = MBEDTLS_BYTE_2(session->ticket_len);
5425
        *p++ = MBEDTLS_BYTE_1(session->ticket_len);
5426
        *p++ = MBEDTLS_BYTE_0(session->ticket_len);
5427
5428
        if (session->ticket != NULL) {
5429
            memcpy(p, session->ticket, session->ticket_len);
5430
            p += session->ticket_len;
5431
        }
5432
5433
        MBEDTLS_PUT_UINT32_BE(session->ticket_lifetime, p, 0);
5434
        p += 4;
5435
    }
5436
#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5437
5438
    /*
5439
     * Misc extension-related info
5440
     */
5441
0
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5442
0
    used += 1;
5443
5444
0
    if (used <= buf_len) {
5445
0
        *p++ = session->mfl_code;
5446
0
    }
5447
0
#endif
5448
5449
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5450
    used += 1;
5451
5452
    if (used <= buf_len) {
5453
        *p++ = (unsigned char) ((session->trunc_hmac) & 0xFF);
5454
    }
5455
#endif
5456
5457
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5458
    used += 1;
5459
5460
    if (used <= buf_len) {
5461
        *p++ = MBEDTLS_BYTE_0(session->encrypt_then_mac);
5462
    }
5463
#endif
5464
5465
    /* Done */
5466
0
    *olen = used;
5467
5468
0
    if (used > buf_len) {
5469
0
        return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
5470
0
    }
5471
5472
0
    return 0;
5473
0
}
5474
5475
/*
5476
 * Public wrapper for ssl_session_save()
5477
 */
5478
int mbedtls_ssl_session_save(const mbedtls_ssl_session *session,
5479
                             unsigned char *buf,
5480
                             size_t buf_len,
5481
                             size_t *olen)
5482
0
{
5483
0
    return ssl_session_save(session, 0, buf, buf_len, olen);
5484
0
}
5485
5486
/*
5487
 * Deserialize session, see mbedtls_ssl_session_save() for format.
5488
 *
5489
 * This internal version is wrapped by a public function that cleans up in
5490
 * case of error, and has an extra option omit_header.
5491
 */
5492
MBEDTLS_CHECK_RETURN_CRITICAL
5493
static int ssl_session_load(mbedtls_ssl_session *session,
5494
                            unsigned char omit_header,
5495
                            const unsigned char *buf,
5496
                            size_t len)
5497
0
{
5498
0
    const unsigned char *p = buf;
5499
0
    const unsigned char * const end = buf + len;
5500
#if defined(MBEDTLS_HAVE_TIME)
5501
    uint64_t start;
5502
#endif
5503
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5504
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5505
    size_t cert_len;
5506
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5507
0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5508
5509
0
    if (!omit_header) {
5510
        /*
5511
         * Check version identifier
5512
         */
5513
5514
0
        if ((size_t) (end - p) < sizeof(ssl_serialized_session_header)) {
5515
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5516
0
        }
5517
5518
0
        if (memcmp(p, ssl_serialized_session_header,
5519
0
                   sizeof(ssl_serialized_session_header)) != 0) {
5520
0
            return MBEDTLS_ERR_SSL_VERSION_MISMATCH;
5521
0
        }
5522
0
        p += sizeof(ssl_serialized_session_header);
5523
0
    }
5524
5525
    /*
5526
     * Time
5527
     */
5528
#if defined(MBEDTLS_HAVE_TIME)
5529
    if (8 > (size_t) (end - p)) {
5530
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5531
    }
5532
5533
    start = ((uint64_t) p[0] << 56) |
5534
            ((uint64_t) p[1] << 48) |
5535
            ((uint64_t) p[2] << 40) |
5536
            ((uint64_t) p[3] << 32) |
5537
            ((uint64_t) p[4] << 24) |
5538
            ((uint64_t) p[5] << 16) |
5539
            ((uint64_t) p[6] <<  8) |
5540
            ((uint64_t) p[7]);
5541
    p += 8;
5542
5543
    session->start = (time_t) start;
5544
#endif /* MBEDTLS_HAVE_TIME */
5545
5546
    /*
5547
     * Basic mandatory fields
5548
     */
5549
0
    if (2 + 1 + 1 + 32 + 48 + 4 > (size_t) (end - p)) {
5550
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5551
0
    }
5552
5553
0
    session->ciphersuite = (p[0] << 8) | p[1];
5554
0
    p += 2;
5555
5556
0
    session->compression = *p++;
5557
5558
0
    session->id_len = *p++;
5559
0
    memcpy(session->id, p, 32);
5560
0
    p += 32;
5561
5562
0
    memcpy(session->master, p, 48);
5563
0
    p += 48;
5564
5565
0
    session->verify_result = ((uint32_t) p[0] << 24) |
5566
0
                             ((uint32_t) p[1] << 16) |
5567
0
                             ((uint32_t) p[2] <<  8) |
5568
0
                             ((uint32_t) p[3]);
5569
0
    p += 4;
5570
5571
    /* Immediately clear invalid pointer values that have been read, in case
5572
     * we exit early before we replaced them with valid ones. */
5573
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5574
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5575
    session->peer_cert = NULL;
5576
#else
5577
0
    session->peer_cert_digest = NULL;
5578
0
#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5579
0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5580
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5581
    session->ticket = NULL;
5582
#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5583
5584
    /*
5585
     * Peer certificate
5586
     */
5587
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5588
#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
5589
    /* Deserialize CRT from the end of the ticket. */
5590
    if (3 > (size_t) (end - p)) {
5591
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5592
    }
5593
5594
    cert_len = (p[0] << 16) | (p[1] << 8) | p[2];
5595
    p += 3;
5596
5597
    if (cert_len != 0) {
5598
        int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5599
5600
        if (cert_len > (size_t) (end - p)) {
5601
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5602
        }
5603
5604
        session->peer_cert = mbedtls_calloc(1, sizeof(mbedtls_x509_crt));
5605
5606
        if (session->peer_cert == NULL) {
5607
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
5608
        }
5609
5610
        mbedtls_x509_crt_init(session->peer_cert);
5611
5612
        if ((ret = mbedtls_x509_crt_parse_der(session->peer_cert,
5613
                                              p, cert_len)) != 0) {
5614
            mbedtls_x509_crt_free(session->peer_cert);
5615
            mbedtls_free(session->peer_cert);
5616
            session->peer_cert = NULL;
5617
            return ret;
5618
        }
5619
5620
        p += cert_len;
5621
    }
5622
#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5623
    /* Deserialize CRT digest from the end of the ticket. */
5624
0
    if (2 > (size_t) (end - p)) {
5625
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5626
0
    }
5627
5628
0
    session->peer_cert_digest_type = (mbedtls_md_type_t) *p++;
5629
0
    session->peer_cert_digest_len  = (size_t) *p++;
5630
5631
0
    if (session->peer_cert_digest_len != 0) {
5632
0
        const mbedtls_md_info_t *md_info =
5633
0
            mbedtls_md_info_from_type(session->peer_cert_digest_type);
5634
0
        if (md_info == NULL) {
5635
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5636
0
        }
5637
0
        if (session->peer_cert_digest_len != mbedtls_md_get_size(md_info)) {
5638
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5639
0
        }
5640
5641
0
        if (session->peer_cert_digest_len > (size_t) (end - p)) {
5642
0
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5643
0
        }
5644
5645
0
        session->peer_cert_digest =
5646
0
            mbedtls_calloc(1, session->peer_cert_digest_len);
5647
0
        if (session->peer_cert_digest == NULL) {
5648
0
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
5649
0
        }
5650
5651
0
        memcpy(session->peer_cert_digest, p,
5652
0
               session->peer_cert_digest_len);
5653
0
        p += session->peer_cert_digest_len;
5654
0
    }
5655
0
#endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
5656
0
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5657
5658
    /*
5659
     * Session ticket and associated data
5660
     */
5661
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
5662
    if (3 > (size_t) (end - p)) {
5663
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5664
    }
5665
5666
    session->ticket_len = (p[0] << 16) | (p[1] << 8) | p[2];
5667
    p += 3;
5668
5669
    if (session->ticket_len != 0) {
5670
        if (session->ticket_len > (size_t) (end - p)) {
5671
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5672
        }
5673
5674
        session->ticket = mbedtls_calloc(1, session->ticket_len);
5675
        if (session->ticket == NULL) {
5676
            return MBEDTLS_ERR_SSL_ALLOC_FAILED;
5677
        }
5678
5679
        memcpy(session->ticket, p, session->ticket_len);
5680
        p += session->ticket_len;
5681
    }
5682
5683
    if (4 > (size_t) (end - p)) {
5684
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5685
    }
5686
5687
    session->ticket_lifetime = ((uint32_t) p[0] << 24) |
5688
                               ((uint32_t) p[1] << 16) |
5689
                               ((uint32_t) p[2] <<  8) |
5690
                               ((uint32_t) p[3]);
5691
    p += 4;
5692
#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
5693
5694
    /*
5695
     * Misc extension-related info
5696
     */
5697
0
#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
5698
0
    if (1 > (size_t) (end - p)) {
5699
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5700
0
    }
5701
5702
0
    session->mfl_code = *p++;
5703
0
#endif
5704
5705
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
5706
    if (1 > (size_t) (end - p)) {
5707
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5708
    }
5709
5710
    session->trunc_hmac = *p++;
5711
#endif
5712
5713
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
5714
    if (1 > (size_t) (end - p)) {
5715
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5716
    }
5717
5718
    session->encrypt_then_mac = *p++;
5719
#endif
5720
5721
    /* Done, should have consumed entire buffer */
5722
0
    if (p != end) {
5723
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5724
0
    }
5725
5726
0
    return 0;
5727
0
}
5728
5729
/*
5730
 * Deserialize session: public wrapper for error cleaning
5731
 */
5732
int mbedtls_ssl_session_load(mbedtls_ssl_session *session,
5733
                             const unsigned char *buf,
5734
                             size_t len)
5735
0
{
5736
0
    int ret = ssl_session_load(session, 0, buf, len);
5737
5738
0
    if (ret != 0) {
5739
0
        mbedtls_ssl_session_free(session);
5740
0
    }
5741
5742
0
    return ret;
5743
0
}
5744
5745
/*
5746
 * Perform a single step of the SSL handshake
5747
 */
5748
int mbedtls_ssl_handshake_step(mbedtls_ssl_context *ssl)
5749
13.8k
{
5750
13.8k
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
5751
5752
13.8k
    if (ssl == NULL || ssl->conf == NULL) {
5753
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5754
0
    }
5755
5756
13.8k
#if defined(MBEDTLS_SSL_CLI_C)
5757
13.8k
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_CLIENT) {
5758
0
        ret = mbedtls_ssl_handshake_client_step(ssl);
5759
0
    }
5760
13.8k
#endif
5761
13.8k
#if defined(MBEDTLS_SSL_SRV_C)
5762
13.8k
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
5763
13.8k
        ret = mbedtls_ssl_handshake_server_step(ssl);
5764
13.8k
    }
5765
13.8k
#endif
5766
5767
13.8k
    return ret;
5768
13.8k
}
5769
5770
/*
5771
 * Perform the SSL handshake
5772
 */
5773
int mbedtls_ssl_handshake(mbedtls_ssl_context *ssl)
5774
9.49k
{
5775
9.49k
    int ret = 0;
5776
5777
    /* Sanity checks */
5778
5779
9.49k
    if (ssl == NULL || ssl->conf == NULL) {
5780
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5781
0
    }
5782
5783
9.49k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
5784
9.49k
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5785
9.49k
        (ssl->f_set_timer == NULL || ssl->f_get_timer == NULL)) {
5786
0
        MBEDTLS_SSL_DEBUG_MSG(1, ("You must use "
5787
0
                                  "mbedtls_ssl_set_timer_cb() for DTLS"));
5788
0
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5789
0
    }
5790
9.49k
#endif /* MBEDTLS_SSL_PROTO_DTLS */
5791
5792
9.49k
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> handshake"));
5793
5794
    /* Main handshake loop */
5795
13.8k
    while (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
5796
13.8k
        ret = mbedtls_ssl_handshake_step(ssl);
5797
5798
13.8k
        if (ret != 0) {
5799
9.49k
            break;
5800
9.49k
        }
5801
13.8k
    }
5802
5803
9.49k
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= handshake"));
5804
5805
9.49k
    return ret;
5806
9.49k
}
5807
5808
#if defined(MBEDTLS_SSL_RENEGOTIATION)
5809
#if defined(MBEDTLS_SSL_SRV_C)
5810
/*
5811
 * Write HelloRequest to request renegotiation on server
5812
 */
5813
MBEDTLS_CHECK_RETURN_CRITICAL
5814
static int ssl_write_hello_request(mbedtls_ssl_context *ssl)
5815
{
5816
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5817
5818
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> write hello request"));
5819
5820
    ssl->out_msglen  = 4;
5821
    ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE;
5822
    ssl->out_msg[0]  = MBEDTLS_SSL_HS_HELLO_REQUEST;
5823
5824
    if ((ret = mbedtls_ssl_write_handshake_msg(ssl)) != 0) {
5825
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_write_handshake_msg", ret);
5826
        return ret;
5827
    }
5828
5829
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= write hello request"));
5830
5831
    return 0;
5832
}
5833
#endif /* MBEDTLS_SSL_SRV_C */
5834
5835
/*
5836
 * Actually renegotiate current connection, triggered by either:
5837
 * - any side: calling mbedtls_ssl_renegotiate(),
5838
 * - client: receiving a HelloRequest during mbedtls_ssl_read(),
5839
 * - server: receiving any handshake message on server during mbedtls_ssl_read() after
5840
 *   the initial handshake is completed.
5841
 * If the handshake doesn't complete due to waiting for I/O, it will continue
5842
 * during the next calls to mbedtls_ssl_renegotiate() or mbedtls_ssl_read() respectively.
5843
 */
5844
int mbedtls_ssl_start_renegotiation(mbedtls_ssl_context *ssl)
5845
{
5846
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
5847
5848
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> renegotiate"));
5849
5850
    if ((ret = ssl_handshake_init(ssl)) != 0) {
5851
        return ret;
5852
    }
5853
5854
    /* RFC 6347 4.2.2: "[...] the HelloRequest will have message_seq = 0 and
5855
     * the ServerHello will have message_seq = 1" */
5856
#if defined(MBEDTLS_SSL_PROTO_DTLS)
5857
    if (ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM &&
5858
        ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_PENDING) {
5859
        if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
5860
            ssl->handshake->out_msg_seq = 1;
5861
        } else {
5862
            ssl->handshake->in_msg_seq = 1;
5863
        }
5864
    }
5865
#endif
5866
5867
    ssl->state = MBEDTLS_SSL_HELLO_REQUEST;
5868
    ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS;
5869
5870
    if ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
5871
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
5872
        return ret;
5873
    }
5874
5875
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= renegotiate"));
5876
5877
    return 0;
5878
}
5879
5880
/*
5881
 * Renegotiate current connection on client,
5882
 * or request renegotiation on server
5883
 */
5884
int mbedtls_ssl_renegotiate(mbedtls_ssl_context *ssl)
5885
{
5886
    int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE;
5887
5888
    if (ssl == NULL || ssl->conf == NULL) {
5889
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5890
    }
5891
5892
#if defined(MBEDTLS_SSL_SRV_C)
5893
    /* On server, just send the request */
5894
    if (ssl->conf->endpoint == MBEDTLS_SSL_IS_SERVER) {
5895
        if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
5896
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5897
        }
5898
5899
        ssl->renego_status = MBEDTLS_SSL_RENEGOTIATION_PENDING;
5900
5901
        /* Did we already try/start sending HelloRequest? */
5902
        if (ssl->out_left != 0) {
5903
            return mbedtls_ssl_flush_output(ssl);
5904
        }
5905
5906
        return ssl_write_hello_request(ssl);
5907
    }
5908
#endif /* MBEDTLS_SSL_SRV_C */
5909
5910
#if defined(MBEDTLS_SSL_CLI_C)
5911
    /*
5912
     * On client, either start the renegotiation process or,
5913
     * if already in progress, continue the handshake
5914
     */
5915
    if (ssl->renego_status != MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS) {
5916
        if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
5917
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
5918
        }
5919
5920
        if ((ret = mbedtls_ssl_start_renegotiation(ssl)) != 0) {
5921
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_start_renegotiation", ret);
5922
            return ret;
5923
        }
5924
    } else {
5925
        if ((ret = mbedtls_ssl_handshake(ssl)) != 0) {
5926
            MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_ssl_handshake", ret);
5927
            return ret;
5928
        }
5929
    }
5930
#endif /* MBEDTLS_SSL_CLI_C */
5931
5932
    return ret;
5933
}
5934
#endif /* MBEDTLS_SSL_RENEGOTIATION */
5935
5936
#if defined(MBEDTLS_X509_CRT_PARSE_C)
5937
static void ssl_key_cert_free(mbedtls_ssl_key_cert *key_cert)
5938
4.38k
{
5939
4.38k
    mbedtls_ssl_key_cert *cur = key_cert, *next;
5940
5941
4.38k
    while (cur != NULL) {
5942
0
        next = cur->next;
5943
0
        mbedtls_free(cur);
5944
0
        cur = next;
5945
0
    }
5946
4.38k
}
5947
#endif /* MBEDTLS_X509_CRT_PARSE_C */
5948
5949
void mbedtls_ssl_handshake_free(mbedtls_ssl_context *ssl)
5950
4.38k
{
5951
4.38k
    mbedtls_ssl_handshake_params *handshake = ssl->handshake;
5952
5953
4.38k
    if (handshake == NULL) {
5954
0
        return;
5955
0
    }
5956
5957
#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
5958
    if (ssl->conf->f_async_cancel != NULL && handshake->async_in_progress != 0) {
5959
        ssl->conf->f_async_cancel(ssl);
5960
        handshake->async_in_progress = 0;
5961
    }
5962
#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
5963
5964
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
5965
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
5966
    mbedtls_md5_free(&handshake->fin_md5);
5967
    mbedtls_sha1_free(&handshake->fin_sha1);
5968
#endif
5969
4.38k
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
5970
4.38k
#if defined(MBEDTLS_SHA256_C)
5971
#if defined(MBEDTLS_USE_PSA_CRYPTO)
5972
    psa_hash_abort(&handshake->fin_sha256_psa);
5973
#else
5974
4.38k
    mbedtls_sha256_free(&handshake->fin_sha256);
5975
4.38k
#endif
5976
4.38k
#endif
5977
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
5978
#if defined(MBEDTLS_USE_PSA_CRYPTO)
5979
    psa_hash_abort(&handshake->fin_sha384_psa);
5980
#else
5981
    mbedtls_sha512_free(&handshake->fin_sha512);
5982
#endif
5983
#endif
5984
4.38k
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
5985
5986
#if defined(MBEDTLS_DHM_C)
5987
    mbedtls_dhm_free(&handshake->dhm_ctx);
5988
#endif
5989
4.38k
#if defined(MBEDTLS_ECDH_C)
5990
4.38k
    mbedtls_ecdh_free(&handshake->ecdh_ctx);
5991
4.38k
#endif
5992
4.38k
#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
5993
4.38k
    mbedtls_ecjpake_free(&handshake->ecjpake_ctx);
5994
4.38k
#if defined(MBEDTLS_SSL_CLI_C)
5995
4.38k
    mbedtls_free(handshake->ecjpake_cache);
5996
4.38k
    handshake->ecjpake_cache = NULL;
5997
4.38k
    handshake->ecjpake_cache_len = 0;
5998
4.38k
#endif
5999
4.38k
#endif
6000
6001
4.38k
#if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
6002
4.38k
    defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
6003
    /* explicit void pointer cast for buggy MS compiler */
6004
4.38k
    mbedtls_free((void *) handshake->curves);
6005
4.38k
#endif
6006
6007
4.38k
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
6008
4.38k
    if (handshake->psk != NULL) {
6009
0
        mbedtls_platform_zeroize(handshake->psk, handshake->psk_len);
6010
0
        mbedtls_free(handshake->psk);
6011
0
    }
6012
4.38k
#endif
6013
6014
#if defined(MBEDTLS_X509_CRT_PARSE_C) && \
6015
    defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
6016
    /*
6017
     * Free only the linked list wrapper, not the keys themselves
6018
     * since the belong to the SNI callback
6019
     */
6020
    if (handshake->sni_key_cert != NULL) {
6021
        mbedtls_ssl_key_cert *cur = handshake->sni_key_cert, *next;
6022
6023
        while (cur != NULL) {
6024
            next = cur->next;
6025
            mbedtls_free(cur);
6026
            cur = next;
6027
        }
6028
    }
6029
#endif /* MBEDTLS_X509_CRT_PARSE_C && MBEDTLS_SSL_SERVER_NAME_INDICATION */
6030
6031
#if defined(MBEDTLS_SSL_ECP_RESTARTABLE_ENABLED)
6032
    mbedtls_x509_crt_restart_free(&handshake->ecrs_ctx);
6033
    if (handshake->ecrs_peer_cert != NULL) {
6034
        mbedtls_x509_crt_free(handshake->ecrs_peer_cert);
6035
        mbedtls_free(handshake->ecrs_peer_cert);
6036
    }
6037
#endif
6038
6039
4.38k
#if defined(MBEDTLS_X509_CRT_PARSE_C) &&        \
6040
4.38k
    !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
6041
4.38k
    mbedtls_pk_free(&handshake->peer_pubkey);
6042
4.38k
#endif /* MBEDTLS_X509_CRT_PARSE_C && !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
6043
6044
4.38k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6045
4.38k
    mbedtls_free(handshake->verify_cookie);
6046
4.38k
    mbedtls_ssl_flight_free(handshake->flight);
6047
4.38k
    mbedtls_ssl_buffering_free(ssl);
6048
4.38k
#endif
6049
6050
#if defined(MBEDTLS_ECDH_C) &&                  \
6051
    defined(MBEDTLS_USE_PSA_CRYPTO)
6052
    psa_destroy_key(handshake->ecdh_psa_privkey);
6053
#endif /* MBEDTLS_ECDH_C && MBEDTLS_USE_PSA_CRYPTO */
6054
6055
4.38k
    mbedtls_platform_zeroize(handshake,
6056
4.38k
                             sizeof(mbedtls_ssl_handshake_params));
6057
6058
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
6059
    /* If the buffers are too big - reallocate. Because of the way Mbed TLS
6060
     * processes datagrams and the fact that a datagram is allowed to have
6061
     * several records in it, it is possible that the I/O buffers are not
6062
     * empty at this stage */
6063
    handle_buffer_resizing(ssl, 1, mbedtls_ssl_get_input_buflen(ssl),
6064
                           mbedtls_ssl_get_output_buflen(ssl));
6065
#endif
6066
4.38k
}
6067
6068
void mbedtls_ssl_session_free(mbedtls_ssl_session *session)
6069
4.38k
{
6070
4.38k
    if (session == NULL) {
6071
0
        return;
6072
0
    }
6073
6074
4.38k
#if defined(MBEDTLS_X509_CRT_PARSE_C)
6075
4.38k
    ssl_clear_peer_cert(session);
6076
4.38k
#endif
6077
6078
#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
6079
    mbedtls_free(session->ticket);
6080
#endif
6081
6082
4.38k
    mbedtls_platform_zeroize(session, sizeof(mbedtls_ssl_session));
6083
4.38k
}
6084
6085
#if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
6086
6087
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
6088
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 1u
6089
#else
6090
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID 0u
6091
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
6092
6093
#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
6094
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 1u
6095
#else
6096
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT 0u
6097
#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
6098
6099
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6100
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 1u
6101
#else
6102
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY 0u
6103
#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
6104
6105
#if defined(MBEDTLS_SSL_ALPN)
6106
#define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 1u
6107
#else
6108
#define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN 0u
6109
#endif /* MBEDTLS_SSL_ALPN */
6110
6111
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT    0
6112
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT     1
6113
#define SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT      2
6114
#define SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT                  3
6115
6116
#define SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG   \
6117
    ((uint32_t) (                              \
6118
         (SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID << \
6119
             SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_CONNECTION_ID_BIT) | \
6120
         (SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT << \
6121
             SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_BADMAC_LIMIT_BIT) | \
6122
         (SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY << \
6123
             SSL_SERIALIZED_CONTEXT_CONFIG_DTLS_ANTI_REPLAY_BIT) | \
6124
         (SSL_SERIALIZED_CONTEXT_CONFIG_ALPN << SSL_SERIALIZED_CONTEXT_CONFIG_ALPN_BIT) | \
6125
         0u))
6126
6127
static unsigned char ssl_serialized_context_header[] = {
6128
    MBEDTLS_VERSION_MAJOR,
6129
    MBEDTLS_VERSION_MINOR,
6130
    MBEDTLS_VERSION_PATCH,
6131
    MBEDTLS_BYTE_1(SSL_SERIALIZED_SESSION_CONFIG_BITFLAG),
6132
    MBEDTLS_BYTE_0(SSL_SERIALIZED_SESSION_CONFIG_BITFLAG),
6133
    MBEDTLS_BYTE_2(SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG),
6134
    MBEDTLS_BYTE_1(SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG),
6135
    MBEDTLS_BYTE_0(SSL_SERIALIZED_CONTEXT_CONFIG_BITFLAG),
6136
};
6137
6138
/*
6139
 * Serialize a full SSL context
6140
 *
6141
 * The format of the serialized data is:
6142
 * (in the presentation language of TLS, RFC 8446 section 3)
6143
 *
6144
 *  // header
6145
 *  opaque mbedtls_version[3];   // major, minor, patch
6146
 *  opaque context_format[5];    // version-specific field determining
6147
 *                               // the format of the remaining
6148
 *                               // serialized data.
6149
 *  Note: When updating the format, remember to keep these
6150
 *        version+format bytes. (We may make their size part of the API.)
6151
 *
6152
 *  // session sub-structure
6153
 *  opaque session<1..2^32-1>;  // see mbedtls_ssl_session_save()
6154
 *  // transform sub-structure
6155
 *  uint8 random[64];           // ServerHello.random+ClientHello.random
6156
 *  uint8 in_cid<0..2^8-1>      // Connection ID: expected incoming value
6157
 *  uint8 out_cid<0..2^8-1>     // Connection ID: outgoing value to use
6158
 *  // fields from ssl_context
6159
 *  uint32 badmac_seen;         // DTLS: number of records with failing MAC
6160
 *  uint64 in_window_top;       // DTLS: last validated record seq_num
6161
 *  uint64 in_window;           // DTLS: bitmask for replay protection
6162
 *  uint8 disable_datagram_packing; // DTLS: only one record per datagram
6163
 *  uint64 cur_out_ctr;         // Record layer: outgoing sequence number
6164
 *  uint16 mtu;                 // DTLS: path mtu (max outgoing fragment size)
6165
 *  uint8 alpn_chosen<0..2^8-1> // ALPN: negotiated application protocol
6166
 *
6167
 * Note that many fields of the ssl_context or sub-structures are not
6168
 * serialized, as they fall in one of the following categories:
6169
 *
6170
 *  1. forced value (eg in_left must be 0)
6171
 *  2. pointer to dynamically-allocated memory (eg session, transform)
6172
 *  3. value can be re-derived from other data (eg session keys from MS)
6173
 *  4. value was temporary (eg content of input buffer)
6174
 *  5. value will be provided by the user again (eg I/O callbacks and context)
6175
 */
6176
int mbedtls_ssl_context_save(mbedtls_ssl_context *ssl,
6177
                             unsigned char *buf,
6178
                             size_t buf_len,
6179
                             size_t *olen)
6180
{
6181
    unsigned char *p = buf;
6182
    size_t used = 0;
6183
    size_t session_len;
6184
    int ret = 0;
6185
6186
    /*
6187
     * Enforce usage restrictions, see "return BAD_INPUT_DATA" in
6188
     * this function's documentation.
6189
     *
6190
     * These are due to assumptions/limitations in the implementation. Some of
6191
     * them are likely to stay (no handshake in progress) some might go away
6192
     * (only DTLS) but are currently used to simplify the implementation.
6193
     */
6194
    /* The initial handshake must be over */
6195
    if (ssl->state != MBEDTLS_SSL_HANDSHAKE_OVER) {
6196
        MBEDTLS_SSL_DEBUG_MSG(1, ("Initial handshake isn't over"));
6197
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6198
    }
6199
    if (ssl->handshake != NULL) {
6200
        MBEDTLS_SSL_DEBUG_MSG(1, ("Handshake isn't completed"));
6201
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6202
    }
6203
    /* Double-check that sub-structures are indeed ready */
6204
    if (ssl->transform == NULL || ssl->session == NULL) {
6205
        MBEDTLS_SSL_DEBUG_MSG(1, ("Serialised structures aren't ready"));
6206
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6207
    }
6208
    /* There must be no pending incoming or outgoing data */
6209
    if (mbedtls_ssl_check_pending(ssl) != 0) {
6210
        MBEDTLS_SSL_DEBUG_MSG(1, ("There is pending incoming data"));
6211
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6212
    }
6213
    if (ssl->out_left != 0) {
6214
        MBEDTLS_SSL_DEBUG_MSG(1, ("There is pending outgoing data"));
6215
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6216
    }
6217
    /* Protocol must be DTLS, not TLS */
6218
    if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
6219
        MBEDTLS_SSL_DEBUG_MSG(1, ("Only DTLS is supported"));
6220
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6221
    }
6222
    /* Version must be 1.2 */
6223
    if (ssl->major_ver != MBEDTLS_SSL_MAJOR_VERSION_3) {
6224
        MBEDTLS_SSL_DEBUG_MSG(1, ("Only version 1.2 supported"));
6225
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6226
    }
6227
    if (ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3) {
6228
        MBEDTLS_SSL_DEBUG_MSG(1, ("Only version 1.2 supported"));
6229
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6230
    }
6231
    /* We must be using an AEAD ciphersuite */
6232
    if (mbedtls_ssl_transform_uses_aead(ssl->transform) != 1) {
6233
        MBEDTLS_SSL_DEBUG_MSG(1, ("Only AEAD ciphersuites supported"));
6234
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6235
    }
6236
    /* Renegotiation must not be enabled */
6237
#if defined(MBEDTLS_SSL_RENEGOTIATION)
6238
    if (ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED) {
6239
        MBEDTLS_SSL_DEBUG_MSG(1, ("Renegotiation must not be enabled"));
6240
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6241
    }
6242
#endif
6243
6244
    /*
6245
     * Version and format identifier
6246
     */
6247
    used += sizeof(ssl_serialized_context_header);
6248
6249
    if (used <= buf_len) {
6250
        memcpy(p, ssl_serialized_context_header,
6251
               sizeof(ssl_serialized_context_header));
6252
        p += sizeof(ssl_serialized_context_header);
6253
    }
6254
6255
    /*
6256
     * Session (length + data)
6257
     */
6258
    ret = ssl_session_save(ssl->session, 1, NULL, 0, &session_len);
6259
    if (ret != MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL) {
6260
        return ret;
6261
    }
6262
6263
    used += 4 + session_len;
6264
    if (used <= buf_len) {
6265
        MBEDTLS_PUT_UINT32_BE(session_len, p, 0);
6266
        p += 4;
6267
6268
        ret = ssl_session_save(ssl->session, 1,
6269
                               p, session_len, &session_len);
6270
        if (ret != 0) {
6271
            return ret;
6272
        }
6273
6274
        p += session_len;
6275
    }
6276
6277
    /*
6278
     * Transform
6279
     */
6280
    used += sizeof(ssl->transform->randbytes);
6281
    if (used <= buf_len) {
6282
        memcpy(p, ssl->transform->randbytes,
6283
               sizeof(ssl->transform->randbytes));
6284
        p += sizeof(ssl->transform->randbytes);
6285
    }
6286
6287
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
6288
    used += 2 + ssl->transform->in_cid_len + ssl->transform->out_cid_len;
6289
    if (used <= buf_len) {
6290
        *p++ = ssl->transform->in_cid_len;
6291
        memcpy(p, ssl->transform->in_cid, ssl->transform->in_cid_len);
6292
        p += ssl->transform->in_cid_len;
6293
6294
        *p++ = ssl->transform->out_cid_len;
6295
        memcpy(p, ssl->transform->out_cid, ssl->transform->out_cid_len);
6296
        p += ssl->transform->out_cid_len;
6297
    }
6298
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
6299
6300
    /*
6301
     * Saved fields from top-level ssl_context structure
6302
     */
6303
#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
6304
    used += 4;
6305
    if (used <= buf_len) {
6306
        MBEDTLS_PUT_UINT32_BE(ssl->badmac_seen, p, 0);
6307
        p += 4;
6308
    }
6309
#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
6310
6311
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6312
    used += 16;
6313
    if (used <= buf_len) {
6314
        MBEDTLS_PUT_UINT64_BE(ssl->in_window_top, p, 0);
6315
        p += 8;
6316
6317
        MBEDTLS_PUT_UINT64_BE(ssl->in_window, p, 0);
6318
        p += 8;
6319
    }
6320
#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
6321
6322
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6323
    used += 1;
6324
    if (used <= buf_len) {
6325
        *p++ = ssl->disable_datagram_packing;
6326
    }
6327
#endif /* MBEDTLS_SSL_PROTO_DTLS */
6328
6329
    used += 8;
6330
    if (used <= buf_len) {
6331
        memcpy(p, ssl->cur_out_ctr, 8);
6332
        p += 8;
6333
    }
6334
6335
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6336
    used += 2;
6337
    if (used <= buf_len) {
6338
        MBEDTLS_PUT_UINT16_BE(ssl->mtu, p, 0);
6339
        p += 2;
6340
    }
6341
#endif /* MBEDTLS_SSL_PROTO_DTLS */
6342
6343
#if defined(MBEDTLS_SSL_ALPN)
6344
    {
6345
        const uint8_t alpn_len = ssl->alpn_chosen
6346
                               ? (uint8_t) strlen(ssl->alpn_chosen)
6347
                               : 0;
6348
6349
        used += 1 + alpn_len;
6350
        if (used <= buf_len) {
6351
            *p++ = alpn_len;
6352
6353
            if (ssl->alpn_chosen != NULL) {
6354
                memcpy(p, ssl->alpn_chosen, alpn_len);
6355
                p += alpn_len;
6356
            }
6357
        }
6358
    }
6359
#endif /* MBEDTLS_SSL_ALPN */
6360
6361
    /*
6362
     * Done
6363
     */
6364
    *olen = used;
6365
6366
    if (used > buf_len) {
6367
        return MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL;
6368
    }
6369
6370
    MBEDTLS_SSL_DEBUG_BUF(4, "saved context", buf, used);
6371
6372
    return mbedtls_ssl_session_reset_int(ssl, 0);
6373
}
6374
6375
/*
6376
 * Helper to get TLS 1.2 PRF from ciphersuite
6377
 * (Duplicates bits of logic from ssl_set_handshake_prfs().)
6378
 */
6379
#if defined(MBEDTLS_SHA256_C) || \
6380
    (defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384))
6381
typedef int (*tls_prf_fn)(const unsigned char *secret, size_t slen,
6382
                          const char *label,
6383
                          const unsigned char *random, size_t rlen,
6384
                          unsigned char *dstbuf, size_t dlen);
6385
static tls_prf_fn ssl_tls12prf_from_cs(int ciphersuite_id)
6386
{
6387
    const mbedtls_ssl_ciphersuite_t * const ciphersuite_info =
6388
        mbedtls_ssl_ciphersuite_from_id(ciphersuite_id);
6389
6390
    if (ciphersuite_info == NULL) {
6391
        return NULL;
6392
    }
6393
6394
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
6395
    if (ciphersuite_info->mac == MBEDTLS_MD_SHA384) {
6396
        return tls_prf_sha384;
6397
    } else
6398
#endif
6399
#if defined(MBEDTLS_SHA256_C)
6400
    {
6401
        if (ciphersuite_info->mac == MBEDTLS_MD_SHA256) {
6402
            return tls_prf_sha256;
6403
        }
6404
    }
6405
#endif
6406
#if !defined(MBEDTLS_SHA256_C) && \
6407
    (!defined(MBEDTLS_SHA512_C) || defined(MBEDTLS_SHA512_NO_SHA384))
6408
    (void) ciphersuite_info;
6409
#endif
6410
    return NULL;
6411
}
6412
6413
#endif /* MBEDTLS_SHA256_C ||
6414
          (MBEDTLS_SHA512_C && !MBEDTLS_SHA512_NO_SHA384) */
6415
6416
/*
6417
 * Deserialize context, see mbedtls_ssl_context_save() for format.
6418
 *
6419
 * This internal version is wrapped by a public function that cleans up in
6420
 * case of error.
6421
 */
6422
MBEDTLS_CHECK_RETURN_CRITICAL
6423
static int ssl_context_load(mbedtls_ssl_context *ssl,
6424
                            const unsigned char *buf,
6425
                            size_t len)
6426
{
6427
    const unsigned char *p = buf;
6428
    const unsigned char * const end = buf + len;
6429
    size_t session_len;
6430
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6431
    tls_prf_fn prf_func = NULL;
6432
6433
    /*
6434
     * The context should have been freshly setup or reset.
6435
     * Give the user an error in case of obvious misuse.
6436
     * (Checking session is useful because it won't be NULL if we're
6437
     * renegotiating, or if the user mistakenly loaded a session first.)
6438
     */
6439
    if (ssl->state != MBEDTLS_SSL_HELLO_REQUEST ||
6440
        ssl->session != NULL) {
6441
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6442
    }
6443
6444
    /*
6445
     * We can't check that the config matches the initial one, but we can at
6446
     * least check it matches the requirements for serializing.
6447
     */
6448
    if (ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ||
6449
        ssl->conf->max_major_ver < MBEDTLS_SSL_MAJOR_VERSION_3 ||
6450
        ssl->conf->min_major_ver > MBEDTLS_SSL_MAJOR_VERSION_3 ||
6451
        ssl->conf->max_minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 ||
6452
        ssl->conf->min_minor_ver > MBEDTLS_SSL_MINOR_VERSION_3 ||
6453
#if defined(MBEDTLS_SSL_RENEGOTIATION)
6454
        ssl->conf->disable_renegotiation != MBEDTLS_SSL_RENEGOTIATION_DISABLED ||
6455
#endif
6456
        0) {
6457
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6458
    }
6459
6460
    MBEDTLS_SSL_DEBUG_BUF(4, "context to load", buf, len);
6461
6462
    /*
6463
     * Check version identifier
6464
     */
6465
    if ((size_t) (end - p) < sizeof(ssl_serialized_context_header)) {
6466
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6467
    }
6468
6469
    if (memcmp(p, ssl_serialized_context_header,
6470
               sizeof(ssl_serialized_context_header)) != 0) {
6471
        return MBEDTLS_ERR_SSL_VERSION_MISMATCH;
6472
    }
6473
    p += sizeof(ssl_serialized_context_header);
6474
6475
    /*
6476
     * Session
6477
     */
6478
    if ((size_t) (end - p) < 4) {
6479
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6480
    }
6481
6482
    session_len = ((size_t) p[0] << 24) |
6483
                  ((size_t) p[1] << 16) |
6484
                  ((size_t) p[2] <<  8) |
6485
                  ((size_t) p[3]);
6486
    p += 4;
6487
6488
    /* This has been allocated by ssl_handshake_init(), called by
6489
     * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */
6490
    ssl->session = ssl->session_negotiate;
6491
    ssl->session_in = ssl->session;
6492
    ssl->session_out = ssl->session;
6493
    ssl->session_negotiate = NULL;
6494
6495
    if ((size_t) (end - p) < session_len) {
6496
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6497
    }
6498
6499
    ret = ssl_session_load(ssl->session, 1, p, session_len);
6500
    if (ret != 0) {
6501
        mbedtls_ssl_session_free(ssl->session);
6502
        return ret;
6503
    }
6504
6505
    p += session_len;
6506
6507
    /*
6508
     * Transform
6509
     */
6510
6511
    /* This has been allocated by ssl_handshake_init(), called by
6512
     * by either mbedtls_ssl_session_reset_int() or mbedtls_ssl_setup(). */
6513
    ssl->transform = ssl->transform_negotiate;
6514
    ssl->transform_in = ssl->transform;
6515
    ssl->transform_out = ssl->transform;
6516
    ssl->transform_negotiate = NULL;
6517
6518
    prf_func = ssl_tls12prf_from_cs(ssl->session->ciphersuite);
6519
    if (prf_func == NULL) {
6520
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6521
    }
6522
6523
    /* Read random bytes and populate structure */
6524
    if ((size_t) (end - p) < sizeof(ssl->transform->randbytes)) {
6525
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6526
    }
6527
6528
    ret = ssl_populate_transform(ssl->transform,
6529
                                 ssl->session->ciphersuite,
6530
                                 ssl->session->master,
6531
#if defined(MBEDTLS_SSL_SOME_MODES_USE_MAC)
6532
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
6533
                                 ssl->session->encrypt_then_mac,
6534
#endif
6535
#if defined(MBEDTLS_SSL_TRUNCATED_HMAC)
6536
                                 ssl->session->trunc_hmac,
6537
#endif
6538
#endif /* MBEDTLS_SSL_SOME_MODES_USE_MAC */
6539
#if defined(MBEDTLS_ZLIB_SUPPORT)
6540
                                 ssl->session->compression,
6541
#endif
6542
                                 prf_func,
6543
                                 p, /* currently pointing to randbytes */
6544
                                 MBEDTLS_SSL_MINOR_VERSION_3, /* (D)TLS 1.2 is forced */
6545
                                 ssl->conf->endpoint,
6546
                                 ssl);
6547
    if (ret != 0) {
6548
        return ret;
6549
    }
6550
6551
    p += sizeof(ssl->transform->randbytes);
6552
6553
#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
6554
    /* Read connection IDs and store them */
6555
    if ((size_t) (end - p) < 1) {
6556
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6557
    }
6558
6559
    ssl->transform->in_cid_len = *p++;
6560
6561
    if ((size_t) (end - p) < ssl->transform->in_cid_len + 1u) {
6562
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6563
    }
6564
6565
    memcpy(ssl->transform->in_cid, p, ssl->transform->in_cid_len);
6566
    p += ssl->transform->in_cid_len;
6567
6568
    ssl->transform->out_cid_len = *p++;
6569
6570
    if ((size_t) (end - p) < ssl->transform->out_cid_len) {
6571
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6572
    }
6573
6574
    memcpy(ssl->transform->out_cid, p, ssl->transform->out_cid_len);
6575
    p += ssl->transform->out_cid_len;
6576
#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
6577
6578
    /*
6579
     * Saved fields from top-level ssl_context structure
6580
     */
6581
#if defined(MBEDTLS_SSL_DTLS_BADMAC_LIMIT)
6582
    if ((size_t) (end - p) < 4) {
6583
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6584
    }
6585
6586
    ssl->badmac_seen = ((uint32_t) p[0] << 24) |
6587
                       ((uint32_t) p[1] << 16) |
6588
                       ((uint32_t) p[2] <<  8) |
6589
                       ((uint32_t) p[3]);
6590
    p += 4;
6591
#endif /* MBEDTLS_SSL_DTLS_BADMAC_LIMIT */
6592
6593
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6594
    if ((size_t) (end - p) < 16) {
6595
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6596
    }
6597
6598
    ssl->in_window_top = ((uint64_t) p[0] << 56) |
6599
                         ((uint64_t) p[1] << 48) |
6600
                         ((uint64_t) p[2] << 40) |
6601
                         ((uint64_t) p[3] << 32) |
6602
                         ((uint64_t) p[4] << 24) |
6603
                         ((uint64_t) p[5] << 16) |
6604
                         ((uint64_t) p[6] <<  8) |
6605
                         ((uint64_t) p[7]);
6606
    p += 8;
6607
6608
    ssl->in_window = ((uint64_t) p[0] << 56) |
6609
                     ((uint64_t) p[1] << 48) |
6610
                     ((uint64_t) p[2] << 40) |
6611
                     ((uint64_t) p[3] << 32) |
6612
                     ((uint64_t) p[4] << 24) |
6613
                     ((uint64_t) p[5] << 16) |
6614
                     ((uint64_t) p[6] <<  8) |
6615
                     ((uint64_t) p[7]);
6616
    p += 8;
6617
#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
6618
6619
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6620
    if ((size_t) (end - p) < 1) {
6621
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6622
    }
6623
6624
    ssl->disable_datagram_packing = *p++;
6625
#endif /* MBEDTLS_SSL_PROTO_DTLS */
6626
6627
    if ((size_t) (end - p) < 8) {
6628
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6629
    }
6630
6631
    memcpy(ssl->cur_out_ctr, p, 8);
6632
    p += 8;
6633
6634
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6635
    if ((size_t) (end - p) < 2) {
6636
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6637
    }
6638
6639
    ssl->mtu = (p[0] << 8) | p[1];
6640
    p += 2;
6641
#endif /* MBEDTLS_SSL_PROTO_DTLS */
6642
6643
#if defined(MBEDTLS_SSL_ALPN)
6644
    {
6645
        uint8_t alpn_len;
6646
        const char **cur;
6647
6648
        if ((size_t) (end - p) < 1) {
6649
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6650
        }
6651
6652
        alpn_len = *p++;
6653
6654
        if (alpn_len != 0 && ssl->conf->alpn_list != NULL) {
6655
            /* alpn_chosen should point to an item in the configured list */
6656
            for (cur = ssl->conf->alpn_list; *cur != NULL; cur++) {
6657
                if (strlen(*cur) == alpn_len &&
6658
                    memcmp(p, cur, alpn_len) == 0) {
6659
                    ssl->alpn_chosen = *cur;
6660
                    break;
6661
                }
6662
            }
6663
        }
6664
6665
        /* can only happen on conf mismatch */
6666
        if (alpn_len != 0 && ssl->alpn_chosen == NULL) {
6667
            return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6668
        }
6669
6670
        p += alpn_len;
6671
    }
6672
#endif /* MBEDTLS_SSL_ALPN */
6673
6674
    /*
6675
     * Forced fields from top-level ssl_context structure
6676
     *
6677
     * Most of them already set to the correct value by mbedtls_ssl_init() and
6678
     * mbedtls_ssl_reset(), so we only need to set the remaining ones.
6679
     */
6680
    ssl->state = MBEDTLS_SSL_HANDSHAKE_OVER;
6681
6682
    ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
6683
    ssl->minor_ver = MBEDTLS_SSL_MINOR_VERSION_3;
6684
6685
    /* Adjust pointers for header fields of outgoing records to
6686
     * the given transform, accounting for explicit IV and CID. */
6687
    mbedtls_ssl_update_out_pointers(ssl, ssl->transform);
6688
6689
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6690
    ssl->in_epoch = 1;
6691
#endif
6692
6693
    /* mbedtls_ssl_reset() leaves the handshake sub-structure allocated,
6694
     * which we don't want - otherwise we'd end up freeing the wrong transform
6695
     * by calling mbedtls_ssl_handshake_wrapup_free_hs_transform()
6696
     * inappropriately. */
6697
    if (ssl->handshake != NULL) {
6698
        mbedtls_ssl_handshake_free(ssl);
6699
        mbedtls_free(ssl->handshake);
6700
        ssl->handshake = NULL;
6701
    }
6702
6703
    /*
6704
     * Done - should have consumed entire buffer
6705
     */
6706
    if (p != end) {
6707
        return MBEDTLS_ERR_SSL_BAD_INPUT_DATA;
6708
    }
6709
6710
    return 0;
6711
}
6712
6713
/*
6714
 * Deserialize context: public wrapper for error cleaning
6715
 */
6716
int mbedtls_ssl_context_load(mbedtls_ssl_context *context,
6717
                             const unsigned char *buf,
6718
                             size_t len)
6719
{
6720
    int ret = ssl_context_load(context, buf, len);
6721
6722
    if (ret != 0) {
6723
        mbedtls_ssl_free(context);
6724
    }
6725
6726
    return ret;
6727
}
6728
#endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
6729
6730
/*
6731
 * Free an SSL context
6732
 */
6733
void mbedtls_ssl_free(mbedtls_ssl_context *ssl)
6734
4.38k
{
6735
4.38k
    if (ssl == NULL) {
6736
0
        return;
6737
0
    }
6738
6739
4.38k
    MBEDTLS_SSL_DEBUG_MSG(2, ("=> free"));
6740
6741
4.38k
    if (ssl->out_buf != NULL) {
6742
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
6743
        size_t out_buf_len = ssl->out_buf_len;
6744
#else
6745
4.38k
        size_t out_buf_len = MBEDTLS_SSL_OUT_BUFFER_LEN;
6746
4.38k
#endif
6747
6748
4.38k
        mbedtls_platform_zeroize(ssl->out_buf, out_buf_len);
6749
4.38k
        mbedtls_free(ssl->out_buf);
6750
4.38k
        ssl->out_buf = NULL;
6751
4.38k
    }
6752
6753
4.38k
    if (ssl->in_buf != NULL) {
6754
#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
6755
        size_t in_buf_len = ssl->in_buf_len;
6756
#else
6757
4.38k
        size_t in_buf_len = MBEDTLS_SSL_IN_BUFFER_LEN;
6758
4.38k
#endif
6759
6760
4.38k
        mbedtls_platform_zeroize(ssl->in_buf, in_buf_len);
6761
4.38k
        mbedtls_free(ssl->in_buf);
6762
4.38k
        ssl->in_buf = NULL;
6763
4.38k
    }
6764
6765
#if defined(MBEDTLS_ZLIB_SUPPORT)
6766
    if (ssl->compress_buf != NULL) {
6767
        mbedtls_platform_zeroize(ssl->compress_buf, MBEDTLS_SSL_COMPRESS_BUFFER_LEN);
6768
        mbedtls_free(ssl->compress_buf);
6769
    }
6770
#endif
6771
6772
4.38k
    if (ssl->transform) {
6773
0
        mbedtls_ssl_transform_free(ssl->transform);
6774
0
        mbedtls_free(ssl->transform);
6775
0
    }
6776
6777
4.38k
    if (ssl->handshake) {
6778
4.38k
        mbedtls_ssl_handshake_free(ssl);
6779
4.38k
        mbedtls_ssl_transform_free(ssl->transform_negotiate);
6780
4.38k
        mbedtls_ssl_session_free(ssl->session_negotiate);
6781
6782
4.38k
        mbedtls_free(ssl->handshake);
6783
4.38k
        mbedtls_free(ssl->transform_negotiate);
6784
4.38k
        mbedtls_free(ssl->session_negotiate);
6785
4.38k
    }
6786
6787
4.38k
    if (ssl->session) {
6788
0
        mbedtls_ssl_session_free(ssl->session);
6789
0
        mbedtls_free(ssl->session);
6790
0
    }
6791
6792
4.38k
#if defined(MBEDTLS_X509_CRT_PARSE_C)
6793
4.38k
    if (ssl->hostname != NULL) {
6794
0
        mbedtls_platform_zeroize(ssl->hostname, strlen(ssl->hostname));
6795
0
        mbedtls_free(ssl->hostname);
6796
0
    }
6797
4.38k
#endif
6798
6799
#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL)
6800
    if (mbedtls_ssl_hw_record_finish != NULL) {
6801
        MBEDTLS_SSL_DEBUG_MSG(2, ("going for mbedtls_ssl_hw_record_finish()"));
6802
        mbedtls_ssl_hw_record_finish(ssl);
6803
    }
6804
#endif
6805
6806
4.38k
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
6807
4.38k
    mbedtls_free(ssl->cli_id);
6808
4.38k
#endif
6809
6810
4.38k
    MBEDTLS_SSL_DEBUG_MSG(2, ("<= free"));
6811
6812
    /* Actually clear after last debug message */
6813
4.38k
    mbedtls_platform_zeroize(ssl, sizeof(mbedtls_ssl_context));
6814
4.38k
}
6815
6816
/*
6817
 * Initialize mbedtls_ssl_config
6818
 */
6819
void mbedtls_ssl_config_init(mbedtls_ssl_config *conf)
6820
4.44k
{
6821
4.44k
    memset(conf, 0, sizeof(mbedtls_ssl_config));
6822
4.44k
}
6823
6824
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6825
static int ssl_preset_default_hashes[] = {
6826
#if defined(MBEDTLS_SHA512_C)
6827
    MBEDTLS_MD_SHA512,
6828
#endif
6829
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
6830
    MBEDTLS_MD_SHA384,
6831
#endif
6832
#if defined(MBEDTLS_SHA256_C)
6833
    MBEDTLS_MD_SHA256,
6834
    MBEDTLS_MD_SHA224,
6835
#endif
6836
#if defined(MBEDTLS_SHA1_C) && defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_KEY_EXCHANGE)
6837
    MBEDTLS_MD_SHA1,
6838
#endif
6839
    MBEDTLS_MD_NONE
6840
};
6841
#endif
6842
6843
static int ssl_preset_suiteb_ciphersuites[] = {
6844
    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256,
6845
    MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,
6846
    0
6847
};
6848
6849
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6850
static int ssl_preset_suiteb_hashes[] = {
6851
    MBEDTLS_MD_SHA256,
6852
    MBEDTLS_MD_SHA384,
6853
    MBEDTLS_MD_NONE
6854
};
6855
#endif
6856
6857
#if defined(MBEDTLS_ECP_C)
6858
static mbedtls_ecp_group_id ssl_preset_suiteb_curves[] = {
6859
#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
6860
    MBEDTLS_ECP_DP_SECP256R1,
6861
#endif
6862
#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
6863
    MBEDTLS_ECP_DP_SECP384R1,
6864
#endif
6865
    MBEDTLS_ECP_DP_NONE
6866
};
6867
#endif
6868
6869
/*
6870
 * Load default in mbedtls_ssl_config
6871
 */
6872
int mbedtls_ssl_config_defaults(mbedtls_ssl_config *conf,
6873
                                int endpoint, int transport, int preset)
6874
4.38k
{
6875
#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
6876
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
6877
#endif
6878
6879
    /* Use the functions here so that they are covered in tests,
6880
     * but otherwise access member directly for efficiency */
6881
4.38k
    mbedtls_ssl_conf_endpoint(conf, endpoint);
6882
4.38k
    mbedtls_ssl_conf_transport(conf, transport);
6883
6884
    /*
6885
     * Things that are common to all presets
6886
     */
6887
4.38k
#if defined(MBEDTLS_SSL_CLI_C)
6888
4.38k
    if (endpoint == MBEDTLS_SSL_IS_CLIENT) {
6889
0
        conf->authmode = MBEDTLS_SSL_VERIFY_REQUIRED;
6890
#if defined(MBEDTLS_SSL_SESSION_TICKETS)
6891
        conf->session_tickets = MBEDTLS_SSL_SESSION_TICKETS_ENABLED;
6892
#endif
6893
0
    }
6894
4.38k
#endif
6895
6896
#if defined(MBEDTLS_ARC4_C)
6897
    conf->arc4_disabled = MBEDTLS_SSL_ARC4_DISABLED;
6898
#endif
6899
6900
#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
6901
    conf->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED;
6902
#endif
6903
6904
#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
6905
    conf->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED;
6906
#endif
6907
6908
#if defined(MBEDTLS_SSL_CBC_RECORD_SPLITTING)
6909
    conf->cbc_record_splitting = MBEDTLS_SSL_CBC_RECORD_SPLITTING_ENABLED;
6910
#endif
6911
6912
4.38k
#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
6913
4.38k
    conf->f_cookie_write = ssl_cookie_write_dummy;
6914
4.38k
    conf->f_cookie_check = ssl_cookie_check_dummy;
6915
4.38k
#endif
6916
6917
4.38k
#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
6918
4.38k
    conf->anti_replay = MBEDTLS_SSL_ANTI_REPLAY_ENABLED;
6919
4.38k
#endif
6920
6921
4.38k
#if defined(MBEDTLS_SSL_SRV_C)
6922
4.38k
    conf->cert_req_ca_list = MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED;
6923
4.38k
#endif
6924
6925
4.38k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6926
4.38k
    conf->hs_timeout_min = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN;
6927
4.38k
    conf->hs_timeout_max = MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX;
6928
4.38k
#endif
6929
6930
#if defined(MBEDTLS_SSL_RENEGOTIATION)
6931
    conf->renego_max_records = MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT;
6932
    memset(conf->renego_period,     0x00, 2);
6933
    memset(conf->renego_period + 2, 0xFF, 6);
6934
#endif
6935
6936
#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
6937
    if (endpoint == MBEDTLS_SSL_IS_SERVER) {
6938
        const unsigned char dhm_p[] =
6939
            MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN;
6940
        const unsigned char dhm_g[] =
6941
            MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN;
6942
6943
        if ((ret = mbedtls_ssl_conf_dh_param_bin(conf,
6944
                                                 dhm_p, sizeof(dhm_p),
6945
                                                 dhm_g, sizeof(dhm_g))) != 0) {
6946
            return ret;
6947
        }
6948
    }
6949
#endif
6950
6951
    /*
6952
     * Preset-specific defaults
6953
     */
6954
4.38k
    switch (preset) {
6955
        /*
6956
         * NSA Suite B
6957
         */
6958
0
        case MBEDTLS_SSL_PRESET_SUITEB:
6959
0
            conf->min_major_ver = MBEDTLS_SSL_MAJOR_VERSION_3;
6960
0
            conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_3; /* TLS 1.2 */
6961
0
            conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
6962
0
            conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
6963
6964
0
            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
6965
0
                conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
6966
0
                    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
6967
0
                        conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
6968
0
                            ssl_preset_suiteb_ciphersuites;
6969
6970
0
#if defined(MBEDTLS_X509_CRT_PARSE_C)
6971
0
            conf->cert_profile = &mbedtls_x509_crt_profile_suiteb;
6972
0
#endif
6973
6974
0
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
6975
0
            conf->sig_hashes = ssl_preset_suiteb_hashes;
6976
0
#endif
6977
6978
0
#if defined(MBEDTLS_ECP_C)
6979
0
            conf->curve_list = ssl_preset_suiteb_curves;
6980
0
#endif
6981
0
            break;
6982
6983
        /*
6984
         * Default
6985
         */
6986
4.38k
        default:
6987
4.38k
            conf->min_major_ver = (MBEDTLS_SSL_MIN_MAJOR_VERSION >
6988
4.38k
                                   MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION) ?
6989
0
                                  MBEDTLS_SSL_MIN_MAJOR_VERSION :
6990
4.38k
                                  MBEDTLS_SSL_MIN_VALID_MAJOR_VERSION;
6991
4.38k
            conf->min_minor_ver = (MBEDTLS_SSL_MIN_MINOR_VERSION >
6992
4.38k
                                   MBEDTLS_SSL_MIN_VALID_MINOR_VERSION) ?
6993
4.38k
                                  MBEDTLS_SSL_MIN_MINOR_VERSION :
6994
4.38k
                                  MBEDTLS_SSL_MIN_VALID_MINOR_VERSION;
6995
4.38k
            conf->max_major_ver = MBEDTLS_SSL_MAX_MAJOR_VERSION;
6996
4.38k
            conf->max_minor_ver = MBEDTLS_SSL_MAX_MINOR_VERSION;
6997
6998
4.38k
#if defined(MBEDTLS_SSL_PROTO_DTLS)
6999
4.38k
            if (transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM) {
7000
4.38k
                conf->min_minor_ver = MBEDTLS_SSL_MINOR_VERSION_2;
7001
4.38k
            }
7002
4.38k
#endif
7003
7004
4.38k
            conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_0] =
7005
4.38k
                conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_1] =
7006
4.38k
                    conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_2] =
7007
4.38k
                        conf->ciphersuite_list[MBEDTLS_SSL_MINOR_VERSION_3] =
7008
4.38k
                            mbedtls_ssl_list_ciphersuites();
7009
7010
4.38k
#if defined(MBEDTLS_X509_CRT_PARSE_C)
7011
4.38k
            conf->cert_profile = &mbedtls_x509_crt_profile_default;
7012
4.38k
#endif
7013
7014
4.38k
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
7015
4.38k
            conf->sig_hashes = ssl_preset_default_hashes;
7016
4.38k
#endif
7017
7018
4.38k
#if defined(MBEDTLS_ECP_C)
7019
4.38k
            conf->curve_list = mbedtls_ecp_grp_id_list();
7020
4.38k
#endif
7021
7022
#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
7023
            conf->dhm_min_bitlen = 1024;
7024
#endif
7025
4.38k
    }
7026
7027
4.38k
    return 0;
7028
4.38k
}
7029
7030
/*
7031
 * Free mbedtls_ssl_config
7032
 */
7033
void mbedtls_ssl_config_free(mbedtls_ssl_config *conf)
7034
4.38k
{
7035
#if defined(MBEDTLS_DHM_C)
7036
    mbedtls_mpi_free(&conf->dhm_P);
7037
    mbedtls_mpi_free(&conf->dhm_G);
7038
#endif
7039
7040
4.38k
#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED)
7041
4.38k
    if (conf->psk != NULL) {
7042
0
        mbedtls_platform_zeroize(conf->psk, conf->psk_len);
7043
0
        mbedtls_free(conf->psk);
7044
0
        conf->psk = NULL;
7045
0
        conf->psk_len = 0;
7046
0
    }
7047
7048
4.38k
    if (conf->psk_identity != NULL) {
7049
0
        mbedtls_platform_zeroize(conf->psk_identity, conf->psk_identity_len);
7050
0
        mbedtls_free(conf->psk_identity);
7051
0
        conf->psk_identity = NULL;
7052
0
        conf->psk_identity_len = 0;
7053
0
    }
7054
4.38k
#endif
7055
7056
4.38k
#if defined(MBEDTLS_X509_CRT_PARSE_C)
7057
4.38k
    ssl_key_cert_free(conf->key_cert);
7058
4.38k
#endif
7059
7060
4.38k
    mbedtls_platform_zeroize(conf, sizeof(mbedtls_ssl_config));
7061
4.38k
}
7062
7063
#if defined(MBEDTLS_PK_C) && \
7064
    (defined(MBEDTLS_RSA_C) || defined(MBEDTLS_ECDSA_C))
7065
/*
7066
 * Convert between MBEDTLS_PK_XXX and SSL_SIG_XXX
7067
 */
7068
unsigned char mbedtls_ssl_sig_from_pk(mbedtls_pk_context *pk)
7069
0
{
7070
#if defined(MBEDTLS_RSA_C)
7071
    if (mbedtls_pk_can_do(pk, MBEDTLS_PK_RSA)) {
7072
        return MBEDTLS_SSL_SIG_RSA;
7073
    }
7074
#endif
7075
0
#if defined(MBEDTLS_ECDSA_C)
7076
0
    if (mbedtls_pk_can_do(pk, MBEDTLS_PK_ECDSA)) {
7077
0
        return MBEDTLS_SSL_SIG_ECDSA;
7078
0
    }
7079
0
#endif
7080
0
    return MBEDTLS_SSL_SIG_ANON;
7081
0
}
7082
7083
unsigned char mbedtls_ssl_sig_from_pk_alg(mbedtls_pk_type_t type)
7084
0
{
7085
0
    switch (type) {
7086
0
        case MBEDTLS_PK_RSA:
7087
0
            return MBEDTLS_SSL_SIG_RSA;
7088
0
        case MBEDTLS_PK_ECDSA:
7089
0
        case MBEDTLS_PK_ECKEY:
7090
0
            return MBEDTLS_SSL_SIG_ECDSA;
7091
0
        default:
7092
0
            return MBEDTLS_SSL_SIG_ANON;
7093
0
    }
7094
0
}
7095
7096
mbedtls_pk_type_t mbedtls_ssl_pk_alg_from_sig(unsigned char sig)
7097
0
{
7098
0
    switch (sig) {
7099
#if defined(MBEDTLS_RSA_C)
7100
        case MBEDTLS_SSL_SIG_RSA:
7101
            return MBEDTLS_PK_RSA;
7102
#endif
7103
0
#if defined(MBEDTLS_ECDSA_C)
7104
0
        case MBEDTLS_SSL_SIG_ECDSA:
7105
0
            return MBEDTLS_PK_ECDSA;
7106
0
#endif
7107
0
        default:
7108
0
            return MBEDTLS_PK_NONE;
7109
0
    }
7110
0
}
7111
#endif /* MBEDTLS_PK_C && ( MBEDTLS_RSA_C || MBEDTLS_ECDSA_C ) */
7112
7113
#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
7114
    defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
7115
7116
/* Find an entry in a signature-hash set matching a given hash algorithm. */
7117
mbedtls_md_type_t mbedtls_ssl_sig_hash_set_find(mbedtls_ssl_sig_hash_set_t *set,
7118
                                                mbedtls_pk_type_t sig_alg)
7119
0
{
7120
0
    switch (sig_alg) {
7121
0
        case MBEDTLS_PK_RSA:
7122
0
            return set->rsa;
7123
0
        case MBEDTLS_PK_ECDSA:
7124
0
            return set->ecdsa;
7125
0
        default:
7126
0
            return MBEDTLS_MD_NONE;
7127
0
    }
7128
0
}
7129
7130
/* Add a signature-hash-pair to a signature-hash set */
7131
void mbedtls_ssl_sig_hash_set_add(mbedtls_ssl_sig_hash_set_t *set,
7132
                                  mbedtls_pk_type_t sig_alg,
7133
                                  mbedtls_md_type_t md_alg)
7134
0
{
7135
0
    switch (sig_alg) {
7136
0
        case MBEDTLS_PK_RSA:
7137
0
            if (set->rsa == MBEDTLS_MD_NONE) {
7138
0
                set->rsa = md_alg;
7139
0
            }
7140
0
            break;
7141
7142
0
        case MBEDTLS_PK_ECDSA:
7143
0
            if (set->ecdsa == MBEDTLS_MD_NONE) {
7144
0
                set->ecdsa = md_alg;
7145
0
            }
7146
0
            break;
7147
7148
0
        default:
7149
0
            break;
7150
0
    }
7151
0
}
7152
7153
/* Allow exactly one hash algorithm for each signature. */
7154
void mbedtls_ssl_sig_hash_set_const_hash(mbedtls_ssl_sig_hash_set_t *set,
7155
                                         mbedtls_md_type_t md_alg)
7156
4.39k
{
7157
4.39k
    set->rsa   = md_alg;
7158
4.39k
    set->ecdsa = md_alg;
7159
4.39k
}
7160
7161
#endif /* MBEDTLS_SSL_PROTO_TLS1_2) &&
7162
          MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
7163
7164
/*
7165
 * Convert from MBEDTLS_SSL_HASH_XXX to MBEDTLS_MD_XXX
7166
 */
7167
mbedtls_md_type_t mbedtls_ssl_md_alg_from_hash(unsigned char hash)
7168
0
{
7169
0
    switch (hash) {
7170
#if defined(MBEDTLS_MD5_C)
7171
        case MBEDTLS_SSL_HASH_MD5:
7172
            return MBEDTLS_MD_MD5;
7173
#endif
7174
#if defined(MBEDTLS_SHA1_C)
7175
        case MBEDTLS_SSL_HASH_SHA1:
7176
            return MBEDTLS_MD_SHA1;
7177
#endif
7178
0
#if defined(MBEDTLS_SHA256_C)
7179
0
        case MBEDTLS_SSL_HASH_SHA224:
7180
0
            return MBEDTLS_MD_SHA224;
7181
0
        case MBEDTLS_SSL_HASH_SHA256:
7182
0
            return MBEDTLS_MD_SHA256;
7183
0
#endif
7184
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
7185
        case MBEDTLS_SSL_HASH_SHA384:
7186
            return MBEDTLS_MD_SHA384;
7187
#endif
7188
#if defined(MBEDTLS_SHA512_C)
7189
        case MBEDTLS_SSL_HASH_SHA512:
7190
            return MBEDTLS_MD_SHA512;
7191
#endif
7192
0
        default:
7193
0
            return MBEDTLS_MD_NONE;
7194
0
    }
7195
0
}
7196
7197
/*
7198
 * Convert from MBEDTLS_MD_XXX to MBEDTLS_SSL_HASH_XXX
7199
 */
7200
unsigned char mbedtls_ssl_hash_from_md_alg(int md)
7201
0
{
7202
0
    switch (md) {
7203
#if defined(MBEDTLS_MD5_C)
7204
        case MBEDTLS_MD_MD5:
7205
            return MBEDTLS_SSL_HASH_MD5;
7206
#endif
7207
#if defined(MBEDTLS_SHA1_C)
7208
        case MBEDTLS_MD_SHA1:
7209
            return MBEDTLS_SSL_HASH_SHA1;
7210
#endif
7211
0
#if defined(MBEDTLS_SHA256_C)
7212
0
        case MBEDTLS_MD_SHA224:
7213
0
            return MBEDTLS_SSL_HASH_SHA224;
7214
0
        case MBEDTLS_MD_SHA256:
7215
0
            return MBEDTLS_SSL_HASH_SHA256;
7216
0
#endif
7217
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
7218
        case MBEDTLS_MD_SHA384:
7219
            return MBEDTLS_SSL_HASH_SHA384;
7220
#endif
7221
#if defined(MBEDTLS_SHA512_C)
7222
        case MBEDTLS_MD_SHA512:
7223
            return MBEDTLS_SSL_HASH_SHA512;
7224
#endif
7225
0
        default:
7226
0
            return MBEDTLS_SSL_HASH_NONE;
7227
0
    }
7228
0
}
7229
7230
#if defined(MBEDTLS_ECP_C)
7231
/*
7232
 * Check if a curve proposed by the peer is in our list.
7233
 * Return 0 if we're willing to use it, -1 otherwise.
7234
 */
7235
int mbedtls_ssl_check_curve(const mbedtls_ssl_context *ssl, mbedtls_ecp_group_id grp_id)
7236
0
{
7237
0
    const mbedtls_ecp_group_id *gid;
7238
7239
0
    if (ssl->conf->curve_list == NULL) {
7240
0
        return -1;
7241
0
    }
7242
7243
0
    for (gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++) {
7244
0
        if (*gid == grp_id) {
7245
0
            return 0;
7246
0
        }
7247
0
    }
7248
7249
0
    return -1;
7250
0
}
7251
7252
/*
7253
 * Same as mbedtls_ssl_check_curve() but takes a TLS ID for the curve.
7254
 */
7255
int mbedtls_ssl_check_curve_tls_id(const mbedtls_ssl_context *ssl, uint16_t tls_id)
7256
0
{
7257
0
    const mbedtls_ecp_curve_info *curve_info =
7258
0
        mbedtls_ecp_curve_info_from_tls_id(tls_id);
7259
0
    if (curve_info == NULL) {
7260
0
        return -1;
7261
0
    }
7262
0
    return mbedtls_ssl_check_curve(ssl, curve_info->grp_id);
7263
0
}
7264
#endif /* MBEDTLS_ECP_C */
7265
7266
#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED)
7267
/*
7268
 * Check if a hash proposed by the peer is in our list.
7269
 * Return 0 if we're willing to use it, -1 otherwise.
7270
 */
7271
int mbedtls_ssl_check_sig_hash(const mbedtls_ssl_context *ssl,
7272
                               mbedtls_md_type_t md)
7273
0
{
7274
0
    const int *cur;
7275
7276
0
    if (ssl->conf->sig_hashes == NULL) {
7277
0
        return -1;
7278
0
    }
7279
7280
0
    for (cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++) {
7281
0
        if (*cur == (int) md) {
7282
0
            return 0;
7283
0
        }
7284
0
    }
7285
7286
0
    return -1;
7287
0
}
7288
#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */
7289
7290
#if defined(MBEDTLS_X509_CRT_PARSE_C)
7291
int mbedtls_ssl_check_cert_usage(const mbedtls_x509_crt *cert,
7292
                                 const mbedtls_ssl_ciphersuite_t *ciphersuite,
7293
                                 int cert_endpoint,
7294
                                 uint32_t *flags)
7295
0
{
7296
0
    int ret = 0;
7297
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7298
    int usage = 0;
7299
#endif
7300
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7301
    const char *ext_oid;
7302
    size_t ext_len;
7303
#endif
7304
7305
0
#if !defined(MBEDTLS_X509_CHECK_KEY_USAGE) &&          \
7306
0
    !defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7307
0
    ((void) cert);
7308
0
    ((void) cert_endpoint);
7309
0
    ((void) flags);
7310
0
#endif
7311
7312
#if defined(MBEDTLS_X509_CHECK_KEY_USAGE)
7313
    if (cert_endpoint == MBEDTLS_SSL_IS_SERVER) {
7314
        /* Server part of the key exchange */
7315
        switch (ciphersuite->key_exchange) {
7316
            case MBEDTLS_KEY_EXCHANGE_RSA:
7317
            case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
7318
                usage = MBEDTLS_X509_KU_KEY_ENCIPHERMENT;
7319
                break;
7320
7321
            case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
7322
            case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
7323
            case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
7324
                usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7325
                break;
7326
7327
            case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
7328
            case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
7329
                usage = MBEDTLS_X509_KU_KEY_AGREEMENT;
7330
                break;
7331
7332
            /* Don't use default: we want warnings when adding new values */
7333
            case MBEDTLS_KEY_EXCHANGE_NONE:
7334
            case MBEDTLS_KEY_EXCHANGE_PSK:
7335
            case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
7336
            case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
7337
            case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
7338
                usage = 0;
7339
        }
7340
    } else {
7341
        /* Client auth: we only implement rsa_sign and mbedtls_ecdsa_sign for now */
7342
        usage = MBEDTLS_X509_KU_DIGITAL_SIGNATURE;
7343
    }
7344
7345
    if (mbedtls_x509_crt_check_key_usage(cert, usage) != 0) {
7346
        *flags |= MBEDTLS_X509_BADCERT_KEY_USAGE;
7347
        ret = -1;
7348
    }
7349
#else
7350
0
    ((void) ciphersuite);
7351
0
#endif /* MBEDTLS_X509_CHECK_KEY_USAGE */
7352
7353
#if defined(MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE)
7354
    if (cert_endpoint == MBEDTLS_SSL_IS_SERVER) {
7355
        ext_oid = MBEDTLS_OID_SERVER_AUTH;
7356
        ext_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_SERVER_AUTH);
7357
    } else {
7358
        ext_oid = MBEDTLS_OID_CLIENT_AUTH;
7359
        ext_len = MBEDTLS_OID_SIZE(MBEDTLS_OID_CLIENT_AUTH);
7360
    }
7361
7362
    if (mbedtls_x509_crt_check_extended_key_usage(cert, ext_oid, ext_len) != 0) {
7363
        *flags |= MBEDTLS_X509_BADCERT_EXT_KEY_USAGE;
7364
        ret = -1;
7365
    }
7366
#endif /* MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE */
7367
7368
0
    return ret;
7369
0
}
7370
#endif /* MBEDTLS_X509_CRT_PARSE_C */
7371
7372
int mbedtls_ssl_set_calc_verify_md(mbedtls_ssl_context *ssl, int md)
7373
0
{
7374
0
#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
7375
0
    if (ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3) {
7376
0
        return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7377
0
    }
7378
7379
0
    switch (md) {
7380
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1)
7381
#if defined(MBEDTLS_MD5_C)
7382
        case MBEDTLS_SSL_HASH_MD5:
7383
            return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7384
#endif
7385
#if defined(MBEDTLS_SHA1_C)
7386
        case MBEDTLS_SSL_HASH_SHA1:
7387
            ssl->handshake->calc_verify = ssl_calc_verify_tls;
7388
            break;
7389
#endif
7390
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */
7391
#if defined(MBEDTLS_SHA512_C) && !defined(MBEDTLS_SHA512_NO_SHA384)
7392
        case MBEDTLS_SSL_HASH_SHA384:
7393
            ssl->handshake->calc_verify = ssl_calc_verify_tls_sha384;
7394
            break;
7395
#endif
7396
0
#if defined(MBEDTLS_SHA256_C)
7397
0
        case MBEDTLS_SSL_HASH_SHA256:
7398
0
            ssl->handshake->calc_verify = ssl_calc_verify_tls_sha256;
7399
0
            break;
7400
0
#endif
7401
0
        default:
7402
0
            return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7403
0
    }
7404
7405
0
    return 0;
7406
#else /* !MBEDTLS_SSL_PROTO_TLS1_2 */
7407
    (void) ssl;
7408
    (void) md;
7409
7410
    return MBEDTLS_ERR_SSL_INVALID_VERIFY_HASH;
7411
#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
7412
0
}
7413
7414
#if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \
7415
    defined(MBEDTLS_SSL_PROTO_TLS1_1)
7416
int mbedtls_ssl_get_key_exchange_md_ssl_tls(mbedtls_ssl_context *ssl,
7417
                                            unsigned char *output,
7418
                                            unsigned char *data, size_t data_len)
7419
{
7420
    int ret = 0;
7421
    mbedtls_md5_context mbedtls_md5;
7422
    mbedtls_sha1_context mbedtls_sha1;
7423
7424
    mbedtls_md5_init(&mbedtls_md5);
7425
    mbedtls_sha1_init(&mbedtls_sha1);
7426
7427
    /*
7428
     * digitally-signed struct {
7429
     *     opaque md5_hash[16];
7430
     *     opaque sha_hash[20];
7431
     * };
7432
     *
7433
     * md5_hash
7434
     *     MD5(ClientHello.random + ServerHello.random
7435
     *                            + ServerParams);
7436
     * sha_hash
7437
     *     SHA(ClientHello.random + ServerHello.random
7438
     *                            + ServerParams);
7439
     */
7440
    if ((ret = mbedtls_md5_starts_ret(&mbedtls_md5)) != 0) {
7441
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md5_starts_ret", ret);
7442
        goto exit;
7443
    }
7444
    if ((ret = mbedtls_md5_update_ret(&mbedtls_md5,
7445
                                      ssl->handshake->randbytes, 64)) != 0) {
7446
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md5_update_ret", ret);
7447
        goto exit;
7448
    }
7449
    if ((ret = mbedtls_md5_update_ret(&mbedtls_md5, data, data_len)) != 0) {
7450
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md5_update_ret", ret);
7451
        goto exit;
7452
    }
7453
    if ((ret = mbedtls_md5_finish_ret(&mbedtls_md5, output)) != 0) {
7454
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md5_finish_ret", ret);
7455
        goto exit;
7456
    }
7457
7458
    if ((ret = mbedtls_sha1_starts_ret(&mbedtls_sha1)) != 0) {
7459
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_sha1_starts_ret", ret);
7460
        goto exit;
7461
    }
7462
    if ((ret = mbedtls_sha1_update_ret(&mbedtls_sha1,
7463
                                       ssl->handshake->randbytes, 64)) != 0) {
7464
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_sha1_update_ret", ret);
7465
        goto exit;
7466
    }
7467
    if ((ret = mbedtls_sha1_update_ret(&mbedtls_sha1, data,
7468
                                       data_len)) != 0) {
7469
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_sha1_update_ret", ret);
7470
        goto exit;
7471
    }
7472
    if ((ret = mbedtls_sha1_finish_ret(&mbedtls_sha1,
7473
                                       output + 16)) != 0) {
7474
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_sha1_finish_ret", ret);
7475
        goto exit;
7476
    }
7477
7478
exit:
7479
    mbedtls_md5_free(&mbedtls_md5);
7480
    mbedtls_sha1_free(&mbedtls_sha1);
7481
7482
    if (ret != 0) {
7483
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7484
                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
7485
    }
7486
7487
    return ret;
7488
7489
}
7490
#endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \
7491
          MBEDTLS_SSL_PROTO_TLS1_1 */
7492
7493
#if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \
7494
    defined(MBEDTLS_SSL_PROTO_TLS1_2)
7495
7496
#if defined(MBEDTLS_USE_PSA_CRYPTO)
7497
int mbedtls_ssl_get_key_exchange_md_tls1_2(mbedtls_ssl_context *ssl,
7498
                                           unsigned char *hash, size_t *hashlen,
7499
                                           unsigned char *data, size_t data_len,
7500
                                           mbedtls_md_type_t md_alg)
7501
{
7502
    psa_status_t status;
7503
    psa_hash_operation_t hash_operation = PSA_HASH_OPERATION_INIT;
7504
    psa_algorithm_t hash_alg = mbedtls_psa_translate_md(md_alg);
7505
7506
    MBEDTLS_SSL_DEBUG_MSG(3, ("Perform PSA-based computation of digest of ServerKeyExchange"));
7507
7508
    if ((status = psa_hash_setup(&hash_operation,
7509
                                 hash_alg)) != PSA_SUCCESS) {
7510
        MBEDTLS_SSL_DEBUG_RET(1, "psa_hash_setup", status);
7511
        goto exit;
7512
    }
7513
7514
    if ((status = psa_hash_update(&hash_operation, ssl->handshake->randbytes,
7515
                                  64)) != PSA_SUCCESS) {
7516
        MBEDTLS_SSL_DEBUG_RET(1, "psa_hash_update", status);
7517
        goto exit;
7518
    }
7519
7520
    if ((status = psa_hash_update(&hash_operation,
7521
                                  data, data_len)) != PSA_SUCCESS) {
7522
        MBEDTLS_SSL_DEBUG_RET(1, "psa_hash_update", status);
7523
        goto exit;
7524
    }
7525
7526
    if ((status = psa_hash_finish(&hash_operation, hash, PSA_HASH_MAX_SIZE,
7527
                                  hashlen)) != PSA_SUCCESS) {
7528
        MBEDTLS_SSL_DEBUG_RET(1, "psa_hash_finish", status);
7529
        goto exit;
7530
    }
7531
7532
exit:
7533
    if (status != PSA_SUCCESS) {
7534
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7535
                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
7536
        switch (status) {
7537
            case PSA_ERROR_NOT_SUPPORTED:
7538
                return MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE;
7539
            case PSA_ERROR_BAD_STATE: /* Intentional fallthrough */
7540
            case PSA_ERROR_BUFFER_TOO_SMALL:
7541
                return MBEDTLS_ERR_MD_BAD_INPUT_DATA;
7542
            case PSA_ERROR_INSUFFICIENT_MEMORY:
7543
                return MBEDTLS_ERR_MD_ALLOC_FAILED;
7544
            default:
7545
                return MBEDTLS_ERR_MD_HW_ACCEL_FAILED;
7546
        }
7547
    }
7548
    return 0;
7549
}
7550
7551
#else
7552
7553
int mbedtls_ssl_get_key_exchange_md_tls1_2(mbedtls_ssl_context *ssl,
7554
                                           unsigned char *hash, size_t *hashlen,
7555
                                           unsigned char *data, size_t data_len,
7556
                                           mbedtls_md_type_t md_alg)
7557
0
{
7558
0
    int ret = 0;
7559
0
    mbedtls_md_context_t ctx;
7560
0
    const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
7561
0
    *hashlen = mbedtls_md_get_size(md_info);
7562
7563
0
    MBEDTLS_SSL_DEBUG_MSG(3, ("Perform mbedtls-based computation of digest of ServerKeyExchange"));
7564
7565
0
    mbedtls_md_init(&ctx);
7566
7567
    /*
7568
     * digitally-signed struct {
7569
     *     opaque client_random[32];
7570
     *     opaque server_random[32];
7571
     *     ServerDHParams params;
7572
     * };
7573
     */
7574
0
    if ((ret = mbedtls_md_setup(&ctx, md_info, 0)) != 0) {
7575
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_setup", ret);
7576
0
        goto exit;
7577
0
    }
7578
0
    if ((ret = mbedtls_md_starts(&ctx)) != 0) {
7579
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_starts", ret);
7580
0
        goto exit;
7581
0
    }
7582
0
    if ((ret = mbedtls_md_update(&ctx, ssl->handshake->randbytes, 64)) != 0) {
7583
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_update", ret);
7584
0
        goto exit;
7585
0
    }
7586
0
    if ((ret = mbedtls_md_update(&ctx, data, data_len)) != 0) {
7587
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_update", ret);
7588
0
        goto exit;
7589
0
    }
7590
0
    if ((ret = mbedtls_md_finish(&ctx, hash)) != 0) {
7591
0
        MBEDTLS_SSL_DEBUG_RET(1, "mbedtls_md_finish", ret);
7592
0
        goto exit;
7593
0
    }
7594
7595
0
exit:
7596
0
    mbedtls_md_free(&ctx);
7597
7598
0
    if (ret != 0) {
7599
0
        mbedtls_ssl_send_alert_message(ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL,
7600
0
                                       MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR);
7601
0
    }
7602
7603
0
    return ret;
7604
0
}
7605
#endif /* MBEDTLS_USE_PSA_CRYPTO */
7606
7607
#endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \
7608
          MBEDTLS_SSL_PROTO_TLS1_2 */
7609
7610
#endif /* MBEDTLS_SSL_TLS_C */