Coverage Report

Created: 2026-11-16 07:12

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/ssl/statem/statem_lib.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4
 *
5
 * Licensed under the Apache License 2.0 (the "License").  You may not use
6
 * this file except in compliance with the License.  You can obtain a copy
7
 * in the file LICENSE in the source distribution or at
8
 * https://www.openssl.org/source/license.html
9
 */
10
11
#include <limits.h>
12
#include <string.h>
13
#include <stdio.h>
14
#include "../ssl_local.h"
15
#include "statem_local.h"
16
#include "internal/cryptlib.h"
17
#include "internal/ssl_unwrap.h"
18
#include <openssl/buffer.h>
19
#include <openssl/core_names.h>
20
#include <openssl/objects.h>
21
#include <openssl/evp.h>
22
#include <openssl/rsa.h>
23
#include <openssl/x509.h>
24
#include <openssl/trace.h>
25
#include <openssl/encoder.h>
26
27
/*
28
 * Map error codes to TLS/SSL alart types.
29
 */
30
typedef struct x509err2alert_st {
31
    int x509err;
32
    int alert;
33
} X509ERR2ALERT;
34
35
/* Fixed value used in the ServerHello random field to identify an HRR */
36
const unsigned char hrrrandom[] = {
37
    0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02,
38
    0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e,
39
    0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c
40
};
41
42
int ossl_statem_set_mutator(SSL *s,
43
    ossl_statem_mutate_handshake_cb mutate_handshake_cb,
44
    ossl_statem_finish_mutate_handshake_cb finish_mutate_handshake_cb,
45
    void *mutatearg)
46
0
{
47
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
48
49
0
    if (sc == NULL)
50
0
        return 0;
51
52
0
    sc->statem.mutate_handshake_cb = mutate_handshake_cb;
53
0
    sc->statem.mutatearg = mutatearg;
54
0
    sc->statem.finish_mutate_handshake_cb = finish_mutate_handshake_cb;
55
56
0
    return 1;
57
0
}
58
59
/*
60
 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
61
 * SSL3_RT_CHANGE_CIPHER_SPEC)
62
 */
63
int ssl3_do_write(SSL_CONNECTION *s, uint8_t type)
64
0
{
65
0
    int ret;
66
0
    size_t written = 0;
67
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
68
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
69
70
    /*
71
     * If we're running the test suite then we may need to mutate the message
72
     * we've been asked to write. Does not happen in normal operation.
73
     */
74
0
    if (s->statem.mutate_handshake_cb != NULL
75
0
        && !s->statem.write_in_progress
76
0
        && type == SSL3_RT_HANDSHAKE
77
0
        && s->init_num >= SSL3_HM_HEADER_LENGTH) {
78
0
        unsigned char *msg;
79
0
        size_t msglen;
80
81
0
        if (!s->statem.mutate_handshake_cb((unsigned char *)s->init_buf->data,
82
0
                s->init_num,
83
0
                &msg, &msglen,
84
0
                s->statem.mutatearg))
85
0
            return -1;
86
0
        if (msglen < SSL3_HM_HEADER_LENGTH
87
0
            || !BUF_MEM_grow(s->init_buf, msglen))
88
0
            return -1;
89
0
        memcpy(s->init_buf->data, msg, msglen);
90
0
        s->init_num = msglen;
91
0
        s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
92
0
        s->statem.finish_mutate_handshake_cb(s->statem.mutatearg);
93
0
        s->statem.write_in_progress = 1;
94
0
    }
95
96
0
    ret = ssl3_write_bytes(ssl, type, &s->init_buf->data[s->init_off],
97
0
        s->init_num, &written);
98
0
    if (ret <= 0)
99
0
        return -1;
100
0
    if (type == SSL3_RT_HANDSHAKE)
101
        /*
102
         * should not be done for 'Hello Request's, but in that case we'll
103
         * ignore the result anyway
104
         * TLS1.3 KeyUpdate and NewSessionTicket do not need to be added
105
         */
106
0
        if (!SSL_CONNECTION_IS_TLS13(s)
107
0
            || (s->statem.hand_state != TLS_ST_SW_SESSION_TICKET
108
0
                && s->statem.hand_state != TLS_ST_CW_KEY_UPDATE
109
0
                && s->statem.hand_state != TLS_ST_SW_KEY_UPDATE))
110
0
            if (!ssl3_finish_mac(s,
111
0
                    (unsigned char *)&s->init_buf->data[s->init_off],
112
0
                    written))
113
0
                return -1;
114
0
    if (written == s->init_num) {
115
0
        s->statem.write_in_progress = 0;
116
0
        if (s->msg_callback)
117
0
            s->msg_callback(1, s->version, type, s->init_buf->data,
118
0
                (size_t)(s->init_off + s->init_num), ussl,
119
0
                s->msg_callback_arg);
120
0
        return 1;
121
0
    }
122
0
    s->init_off += written;
123
0
    s->init_num -= written;
124
0
    return 0;
125
0
}
126
127
int tls_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
128
0
{
129
0
    size_t msglen;
130
131
0
    if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
132
0
        || !WPACKET_get_length(pkt, &msglen)
133
0
        || msglen > INT_MAX)
134
0
        return 0;
135
0
    s->init_num = msglen;
136
0
    s->init_off = 0;
137
138
0
    return 1;
139
0
}
140
141
int tls_setup_handshake(SSL_CONNECTION *s)
142
0
{
143
0
    int ver_min, ver_max, ok;
144
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
145
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
146
147
0
    if (!ssl3_init_finished_mac(s)) {
148
        /* SSLfatal() already called */
149
0
        return 0;
150
0
    }
151
152
    /* Reset any extension flags */
153
0
    memset(s->ext.extflags, 0, sizeof(s->ext.extflags));
154
155
0
    if (ssl_get_min_max_version(s, &ver_min, &ver_max, NULL) != 0) {
156
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_NO_PROTOCOLS_AVAILABLE);
157
0
        return 0;
158
0
    }
159
160
    /* Sanity check that we have MD5-SHA1 if we need it */
161
0
    if (sctx->ssl_digest_methods[SSL_MD_MD5_SHA1_IDX] == NULL) {
162
0
        const int version1_2 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_2_VERSION
163
0
                                                         : TLS1_2_VERSION;
164
0
        const int version1_1 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_VERSION
165
0
                                                         : TLS1_1_VERSION;
166
167
        /* We don't have MD5-SHA1 - do we need it? */
168
0
        if (ssl_version_cmp(s, ver_max, version1_1) <= 0) {
169
0
            SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
170
0
                SSL_R_NO_SUITABLE_DIGEST_ALGORITHM,
171
0
                "The max supported SSL/TLS version needs the"
172
0
                " MD5-SHA1 digest but it is not available"
173
0
                " in the loaded providers. Use (D)TLSv1.2 or"
174
0
                " above, or load different providers");
175
0
            return 0;
176
0
        }
177
178
0
        ok = 1;
179
180
        /* Don't allow TLSv1.1 or below to be negotiated */
181
0
        if (ssl_version_cmp(s, ver_min, version1_2) < 0)
182
0
            ok = SSL_set_min_proto_version(ssl, version1_2);
183
0
        if (!ok) {
184
            /* Shouldn't happen */
185
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
186
0
            return 0;
187
0
        }
188
0
    }
189
190
0
    ok = 0;
191
0
    if (s->server) {
192
0
        STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
193
0
        int i;
194
195
        /*
196
         * Sanity check that the maximum version we accept has ciphers
197
         * enabled. For clients we do this check during construction of the
198
         * ClientHello.
199
         */
200
0
        for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
201
0
            const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
202
0
            int cipher_minprotover = SSL_CONNECTION_IS_DTLS(s)
203
0
                ? c->min_dtls
204
0
                : c->min_tls;
205
0
            int cipher_maxprotover = SSL_CONNECTION_IS_DTLS(s)
206
0
                ? c->max_dtls
207
0
                : c->max_tls;
208
209
0
            if (cipher_minprotover > 0 && cipher_maxprotover > 0
210
0
                && ssl_version_cmp(s, ver_max, cipher_minprotover) >= 0
211
0
                && ssl_version_cmp(s, ver_max, cipher_maxprotover) <= 0) {
212
0
                ok = 1;
213
0
                break;
214
0
            }
215
0
        }
216
0
        if (!ok) {
217
0
            SSLfatal_data(s, SSL_AD_HANDSHAKE_FAILURE,
218
0
                SSL_R_NO_CIPHERS_AVAILABLE,
219
0
                "No ciphers enabled for max supported "
220
0
                "SSL/TLS version");
221
0
            return 0;
222
0
        }
223
0
        if (SSL_IS_FIRST_HANDSHAKE(s)) {
224
            /* N.B. s->session_ctx == s->ctx here */
225
0
            ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_accept);
226
0
        } else {
227
            /* N.B. s->ctx may not equal s->session_ctx */
228
0
            ssl_tsan_counter(sctx, &sctx->stats.sess_accept_renegotiate);
229
230
0
            s->s3.tmp.cert_request = 0;
231
0
        }
232
0
    } else {
233
0
        if (SSL_IS_FIRST_HANDSHAKE(s))
234
0
            ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_connect);
235
0
        else
236
0
            ssl_tsan_counter(s->session_ctx,
237
0
                &s->session_ctx->stats.sess_connect_renegotiate);
238
239
        /* mark client_random uninitialized */
240
0
        memset(s->s3.client_random, 0, sizeof(s->s3.client_random));
241
0
        s->hit = 0;
242
243
0
        s->s3.tmp.cert_req = 0;
244
245
0
        if (SSL_CONNECTION_IS_DTLS(s))
246
0
            s->statem.use_timer = 1;
247
0
    }
248
249
0
    return 1;
250
0
}
251
252
/*
253
 * Size of the to-be-signed TLS13 data, without the hash size itself:
254
 * 64 bytes of value 32, 33 context bytes, 1 byte separator
255
 */
256
0
#define TLS13_TBS_START_SIZE 64
257
0
#define TLS13_TBS_PREAMBLE_SIZE (TLS13_TBS_START_SIZE + 33 + 1)
258
259
static int get_cert_verify_tbs_data(SSL_CONNECTION *s, unsigned char *tls13tbs,
260
    void **hdata, size_t *hdatalen)
261
0
{
262
    /* ASCII: "TLS 1.3, server CertificateVerify", in hex for EBCDIC compatibility */
263
0
    static const char servercontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x73\x65\x72"
264
0
                                        "\x76\x65\x72\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
265
    /* ASCII: "TLS 1.3, client CertificateVerify", in hex for EBCDIC compatibility */
266
0
    static const char clientcontext[] = "\x54\x4c\x53\x20\x31\x2e\x33\x2c\x20\x63\x6c\x69"
267
0
                                        "\x65\x6e\x74\x20\x43\x65\x72\x74\x69\x66\x69\x63\x61\x74\x65\x56\x65\x72\x69\x66\x79";
268
269
0
    if (SSL_CONNECTION_IS_VERSION13(s)) {
270
0
        size_t hashlen;
271
272
        /* Set the first 64 bytes of to-be-signed data to octet 32 */
273
0
        memset(tls13tbs, 32, TLS13_TBS_START_SIZE);
274
        /* This copies the 33 bytes of context plus the 0 separator byte */
275
0
        if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
276
0
            || s->statem.hand_state == TLS_ST_SW_CERT_VRFY)
277
0
            strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, servercontext);
278
0
        else
279
0
            strcpy((char *)tls13tbs + TLS13_TBS_START_SIZE, clientcontext);
280
281
        /*
282
         * If we're currently reading then we need to use the saved handshake
283
         * hash value. We can't use the current handshake hash state because
284
         * that includes the CertVerify itself.
285
         */
286
0
        if (s->statem.hand_state == TLS_ST_CR_CERT_VRFY
287
0
            || s->statem.hand_state == TLS_ST_SR_CERT_VRFY) {
288
0
            memcpy(tls13tbs + TLS13_TBS_PREAMBLE_SIZE, s->cert_verify_hash,
289
0
                s->cert_verify_hash_len);
290
0
            hashlen = s->cert_verify_hash_len;
291
0
        } else if (!ssl_handshake_hash(s, tls13tbs + TLS13_TBS_PREAMBLE_SIZE,
292
0
                       EVP_MAX_MD_SIZE, &hashlen)) {
293
            /* SSLfatal() already called */
294
0
            return 0;
295
0
        }
296
297
0
        *hdata = tls13tbs;
298
0
        *hdatalen = TLS13_TBS_PREAMBLE_SIZE + hashlen;
299
0
    } else {
300
0
        size_t retlen;
301
0
        long retlen_l;
302
303
0
        retlen = retlen_l = BIO_get_mem_data(s->s3.handshake_buffer, hdata);
304
0
        if (retlen_l <= 0) {
305
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
306
0
            return 0;
307
0
        }
308
0
        *hdatalen = retlen;
309
0
    }
310
311
0
    return 1;
312
0
}
313
314
CON_FUNC_RETURN tls_construct_cert_verify(SSL_CONNECTION *s, WPACKET *pkt)
315
0
{
316
0
    EVP_PKEY *pkey = NULL;
317
0
    const EVP_MD *md = NULL;
318
0
    EVP_MD_CTX *mctx = NULL;
319
0
    EVP_PKEY_CTX *pctx = NULL;
320
0
    size_t hdatalen = 0, siglen = 0;
321
0
    void *hdata;
322
0
    unsigned char *sig = NULL;
323
0
    unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
324
0
    const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
325
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
326
0
    OSSL_PARAM params[3], *p = params;
327
328
0
    if (lu == NULL || s->s3.tmp.cert == NULL) {
329
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
330
0
        goto err;
331
0
    }
332
0
    pkey = s->s3.tmp.cert->privatekey;
333
334
0
    if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
335
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
336
0
        goto err;
337
0
    }
338
339
0
    mctx = EVP_MD_CTX_new();
340
0
    if (mctx == NULL) {
341
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
342
0
        goto err;
343
0
    }
344
345
    /* Get the data to be signed */
346
0
    if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
347
        /* SSLfatal() already called */
348
0
        goto err;
349
0
    }
350
351
0
    if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
352
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
353
0
        goto err;
354
0
    }
355
356
    /*
357
     * To avoid problems with older RSA providers we must also pass the digest
358
     * name when passing any other parameters.
359
     */
360
0
    *p++ = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_TLS_VERSION, &s->version);
361
0
    if (md != NULL)
362
0
        *p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST,
363
0
            (char *)EVP_MD_get0_name(md), 0);
364
0
    *p = OSSL_PARAM_construct_end();
365
366
0
    if (EVP_DigestSignInit_ex(mctx, &pctx,
367
0
            md == NULL ? NULL : EVP_MD_get0_name(md),
368
0
            sctx->libctx, sctx->propq, pkey, params)
369
0
        <= 0) {
370
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
371
0
        goto err;
372
0
    }
373
374
0
    if (lu->sig == EVP_PKEY_RSA_PSS) {
375
0
        if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
376
0
            || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
377
0
                   RSA_PSS_SALTLEN_DIGEST)
378
0
                <= 0) {
379
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
380
0
            goto err;
381
0
        }
382
0
    }
383
384
    /*
385
     * Here we *must* use EVP_DigestSign() because Ed25519/Ed448 does not
386
     * support streaming via EVP_DigestSignUpdate/EVP_DigestSignFinal
387
     */
388
0
    if (EVP_DigestSign(mctx, NULL, &siglen, hdata, hdatalen) <= 0) {
389
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
390
0
        goto err;
391
0
    }
392
0
    sig = OPENSSL_malloc(siglen);
393
0
    if (sig == NULL
394
0
        || EVP_DigestSign(mctx, sig, &siglen, hdata, hdatalen) <= 0) {
395
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
396
0
        goto err;
397
0
    }
398
399
0
#ifndef OPENSSL_NO_GOST
400
0
    {
401
0
        int pktype = lu->sig;
402
403
0
        if (pktype == NID_id_GostR3410_2001
404
0
            || pktype == NID_id_GostR3410_2012_256
405
0
            || pktype == NID_id_GostR3410_2012_512)
406
0
            BUF_reverse(sig, NULL, siglen);
407
0
    }
408
0
#endif
409
410
0
    if (!WPACKET_sub_memcpy_u16(pkt, sig, siglen)) {
411
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
412
0
        goto err;
413
0
    }
414
415
    /* Digest cached records and discard handshake buffer */
416
0
    if (!ssl3_digest_cached_records(s, 0)) {
417
        /* SSLfatal() already called */
418
0
        goto err;
419
0
    }
420
421
0
    OPENSSL_free(sig);
422
0
    EVP_MD_CTX_free(mctx);
423
0
    return CON_FUNC_SUCCESS;
424
0
err:
425
0
    OPENSSL_free(sig);
426
0
    EVP_MD_CTX_free(mctx);
427
0
    return CON_FUNC_ERROR;
428
0
}
429
430
MSG_PROCESS_RETURN tls_process_cert_verify(SSL_CONNECTION *s, PACKET *pkt)
431
0
{
432
0
    EVP_PKEY *pkey = NULL;
433
0
    const unsigned char *data;
434
0
#ifndef OPENSSL_NO_GOST
435
0
    unsigned char *gost_data = NULL;
436
0
#endif
437
0
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
438
0
    int j;
439
0
    unsigned int len;
440
0
    const EVP_MD *md = NULL;
441
0
    size_t hdatalen = 0;
442
0
    void *hdata;
443
0
    unsigned char tls13tbs[TLS13_TBS_PREAMBLE_SIZE + EVP_MAX_MD_SIZE];
444
0
    EVP_MD_CTX *mctx = EVP_MD_CTX_new();
445
0
    EVP_PKEY_CTX *pctx = NULL;
446
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
447
0
    OSSL_PARAM params[3], *p = params;
448
449
0
    if (mctx == NULL) {
450
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
451
0
        goto err;
452
0
    }
453
454
0
    pkey = tls_get_peer_pkey(s);
455
0
    if (pkey == NULL) {
456
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
457
0
        goto err;
458
0
    }
459
460
0
    if (ssl_cert_lookup_by_pkey(pkey, NULL, sctx) == NULL) {
461
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
462
0
            SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
463
0
        goto err;
464
0
    }
465
466
0
    if (SSL_USE_SIGALGS(s)) {
467
0
        unsigned int sigalg;
468
469
0
        if (!PACKET_get_net_2(pkt, &sigalg)) {
470
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
471
0
            goto err;
472
0
        }
473
0
        if (tls12_check_peer_sigalg(s, sigalg, pkey) <= 0) {
474
            /* SSLfatal() already called */
475
0
            goto err;
476
0
        }
477
0
    } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
478
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
479
0
            SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
480
0
        goto err;
481
0
    }
482
483
0
    if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
484
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
485
0
        goto err;
486
0
    }
487
488
0
    if (SSL_USE_SIGALGS(s))
489
0
        OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
490
0
            md == NULL ? "n/a" : EVP_MD_get0_name(md));
491
492
    /* Check for broken implementations of GOST ciphersuites */
493
    /*
494
     * If key is GOST and len is exactly 64 or 128, it is signature without
495
     * length field (CryptoPro implementations at least till TLS 1.2)
496
     */
497
0
#ifndef OPENSSL_NO_GOST
498
0
    if (!SSL_USE_SIGALGS(s)
499
0
        && ((PACKET_remaining(pkt) == 64
500
0
                && (EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2001
501
0
                    || EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_256))
502
0
            || (PACKET_remaining(pkt) == 128
503
0
                && EVP_PKEY_get_id(pkey) == NID_id_GostR3410_2012_512))) {
504
0
        len = (unsigned int)PACKET_remaining(pkt);
505
0
    } else
506
0
#endif
507
0
        if (!PACKET_get_net_2(pkt, &len)) {
508
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
509
0
        goto err;
510
0
    }
511
512
0
    if (!PACKET_get_bytes(pkt, &data, len)) {
513
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
514
0
        goto err;
515
0
    }
516
0
    if (PACKET_remaining(pkt) != 0) {
517
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
518
0
        goto err;
519
0
    }
520
521
0
    if (!get_cert_verify_tbs_data(s, tls13tbs, &hdata, &hdatalen)) {
522
        /* SSLfatal() already called */
523
0
        goto err;
524
0
    }
525
526
0
    OSSL_TRACE1(TLS, "Using client verify alg %s\n",
527
0
        md == NULL ? "n/a" : EVP_MD_get0_name(md));
528
529
    /*
530
     * To avoid problems with older RSA providers we must also pass the digest
531
     * name when passing any other parameters.
532
     */
533
0
    *p++ = OSSL_PARAM_construct_int(OSSL_SIGNATURE_PARAM_TLS_VERSION, &s->version);
534
0
    if (md != NULL)
535
0
        *p++ = OSSL_PARAM_construct_utf8_string(OSSL_SIGNATURE_PARAM_DIGEST,
536
0
            (char *)EVP_MD_get0_name(md), 0);
537
0
    *p = OSSL_PARAM_construct_end();
538
539
0
    if (EVP_DigestVerifyInit_ex(mctx, &pctx,
540
0
            md == NULL ? NULL : EVP_MD_get0_name(md),
541
0
            sctx->libctx, sctx->propq, pkey, params)
542
0
        <= 0) {
543
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
544
0
        goto err;
545
0
    }
546
0
#ifndef OPENSSL_NO_GOST
547
0
    {
548
0
        int pktype = EVP_PKEY_get_id(pkey);
549
0
        if (pktype == NID_id_GostR3410_2001
550
0
            || pktype == NID_id_GostR3410_2012_256
551
0
            || pktype == NID_id_GostR3410_2012_512) {
552
0
            if ((gost_data = OPENSSL_malloc(len)) == NULL)
553
0
                goto err;
554
0
            BUF_reverse(gost_data, data, len);
555
0
            data = gost_data;
556
0
        }
557
0
    }
558
0
#endif
559
560
0
    if (SSL_USE_PSS(s)) {
561
0
        if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
562
0
            || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
563
0
                   RSA_PSS_SALTLEN_DIGEST)
564
0
                <= 0) {
565
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
566
0
            goto err;
567
0
        }
568
0
    }
569
570
0
    j = EVP_DigestVerify(mctx, data, len, hdata, hdatalen);
571
0
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
572
    /* Ignore bad signatures when fuzzing */
573
0
    if (SSL_IS_QUIC_HANDSHAKE(s))
574
0
        j = 1;
575
0
#endif
576
0
    if (j <= 0) {
577
0
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
578
0
        goto err;
579
0
    }
580
581
    /*
582
     * In (D)TLSv1.3 on the client side we make sure we prepare the client
583
     * certificate after the CertVerify instead of when we get the
584
     * CertificateRequest. This is because in (D)TLSv1.3 the CertificateRequest
585
     * comes *before* the Certificate message. In (D)TLSv1.2 it comes after. We
586
     * want to make sure that SSL_get1_peer_certificate() will return the actual
587
     * server certificate from the client_cert_cb callback.
588
     */
589
0
    if (!s->server && SSL_CONNECTION_IS_VERSION13(s) && s->s3.tmp.cert_req == 1)
590
0
        ret = MSG_PROCESS_CONTINUE_PROCESSING;
591
0
    else
592
0
        ret = MSG_PROCESS_CONTINUE_READING;
593
0
err:
594
0
    BIO_free(s->s3.handshake_buffer);
595
0
    s->s3.handshake_buffer = NULL;
596
0
    EVP_MD_CTX_free(mctx);
597
0
#ifndef OPENSSL_NO_GOST
598
0
    OPENSSL_free(gost_data);
599
0
#endif
600
0
    return ret;
601
0
}
602
603
CON_FUNC_RETURN tls_construct_finished(SSL_CONNECTION *s, WPACKET *pkt)
604
0
{
605
0
    size_t finish_md_len;
606
0
    const char *sender;
607
0
    size_t slen;
608
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
609
610
    /* This is a real handshake so make sure we clean it up at the end */
611
0
    if (!s->server && s->post_handshake_auth != SSL_PHA_REQUESTED)
612
0
        s->statem.cleanuphand = 1;
613
614
    /*
615
     * If we attempted to write early data or we're in middlebox compat mode
616
     * then we deferred changing the handshake write keys to the last possible
617
     * moment. If we didn't already do this when we sent the client certificate
618
     * then we need to do it now.
619
     */
620
0
    if (SSL_CONNECTION_IS_VERSION13(s)
621
0
        && !s->server
622
0
        && !SSL_IS_QUIC_HANDSHAKE(s)
623
0
        && (s->early_data_state != SSL_EARLY_DATA_NONE
624
0
            || SSL_CONNECTION_MIDDLEBOX_IS_ENABLED(s))
625
0
        && s->s3.tmp.cert_req == 0
626
0
        && (!ssl->method->ssl3_enc->change_cipher_state(s,
627
0
            SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
628
0
        ;
629
        /* SSLfatal() already called */
630
0
        return CON_FUNC_ERROR;
631
0
    }
632
633
0
    if (s->server) {
634
0
        sender = ssl->method->ssl3_enc->server_finished_label;
635
0
        slen = ssl->method->ssl3_enc->server_finished_label_len;
636
0
    } else {
637
0
        sender = ssl->method->ssl3_enc->client_finished_label;
638
0
        slen = ssl->method->ssl3_enc->client_finished_label_len;
639
0
    }
640
641
0
    finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s,
642
0
        sender, slen,
643
0
        s->s3.tmp.finish_md);
644
0
    if (finish_md_len == 0) {
645
        /* SSLfatal() already called */
646
0
        return CON_FUNC_ERROR;
647
0
    }
648
649
0
    s->s3.tmp.finish_md_len = finish_md_len;
650
651
0
    if (!WPACKET_memcpy(pkt, s->s3.tmp.finish_md, finish_md_len)) {
652
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
653
0
        return CON_FUNC_ERROR;
654
0
    }
655
656
    /*
657
     * Log the master secret, if logging is enabled. We don't log it for
658
     * (D)TLSv1.3: there's a different key schedule for that.
659
     */
660
0
    if (!SSL_CONNECTION_IS_VERSION13(s)
661
0
        && !ssl_log_secret(s, MASTER_SECRET_LABEL, s->session->master_key,
662
0
            s->session->master_key_length)) {
663
        /* SSLfatal() already called */
664
0
        return CON_FUNC_ERROR;
665
0
    }
666
667
    /*
668
     * Copy the finished so we can use it for renegotiation checks
669
     */
670
0
    if (!ossl_assert(finish_md_len <= EVP_MAX_MD_SIZE)) {
671
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
672
0
        return CON_FUNC_ERROR;
673
0
    }
674
0
    if (!s->server) {
675
0
        memcpy(s->s3.previous_client_finished, s->s3.tmp.finish_md,
676
0
            finish_md_len);
677
0
        s->s3.previous_client_finished_len = finish_md_len;
678
0
    } else {
679
0
        memcpy(s->s3.previous_server_finished, s->s3.tmp.finish_md,
680
0
            finish_md_len);
681
0
        s->s3.previous_server_finished_len = finish_md_len;
682
0
    }
683
684
0
    return CON_FUNC_SUCCESS;
685
0
}
686
687
CON_FUNC_RETURN tls_construct_key_update(SSL_CONNECTION *s, WPACKET *pkt)
688
0
{
689
0
    if (!WPACKET_put_bytes_u8(pkt, s->key_update)) {
690
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
691
0
        return CON_FUNC_ERROR;
692
0
    }
693
694
0
    s->key_update = SSL_KEY_UPDATE_NONE;
695
0
    return CON_FUNC_SUCCESS;
696
0
}
697
698
MSG_PROCESS_RETURN tls_process_key_update(SSL_CONNECTION *s, PACKET *pkt)
699
0
{
700
0
    unsigned int updatetype;
701
702
    /*
703
     * A KeyUpdate message signals a key change so the end of the message must
704
     * be on a record boundary.
705
     */
706
0
    if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
707
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
708
0
        return MSG_PROCESS_ERROR;
709
0
    }
710
711
0
    if (!PACKET_get_1(pkt, &updatetype)
712
0
        || PACKET_remaining(pkt) != 0) {
713
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_KEY_UPDATE);
714
0
        return MSG_PROCESS_ERROR;
715
0
    }
716
717
    /*
718
     * There are only two defined key update types. Fail if we get a value we
719
     * didn't recognise.
720
     */
721
0
    if (updatetype != SSL_KEY_UPDATE_NOT_REQUESTED
722
0
        && updatetype != SSL_KEY_UPDATE_REQUESTED) {
723
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_UPDATE);
724
0
        return MSG_PROCESS_ERROR;
725
0
    }
726
727
    /*
728
     * If we get a request for us to update our sending keys too then, we need
729
     * to additionally send a KeyUpdate message. However that message should
730
     * not also request an update (otherwise we get into an infinite loop).
731
     * For DTLS1.3 specifically, this doesn't go through the public
732
     * SSL_key_update() API, so it has to set in_init itself: without it,
733
     * nothing tells a later SSL_write()/SSL_do_handshake() call to
734
     * re-enter the state machine and notice key_update is no longer
735
     * SSL_KEY_UPDATE_NONE, and the scheduled KeyUpdate would never
736
     * actually get sent.
737
     */
738
0
    if (updatetype == SSL_KEY_UPDATE_REQUESTED) {
739
0
        s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
740
0
        if (SSL_CONNECTION_IS_DTLS13(s))
741
0
            ossl_statem_set_in_init(s, 1);
742
0
    }
743
744
0
    if (!tls13_update_key(s, 0)) {
745
        /* SSLfatal() already called */
746
0
        return MSG_PROCESS_ERROR;
747
0
    }
748
749
0
    return MSG_PROCESS_FINISHED_READING;
750
0
}
751
752
/*
753
 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
754
 * to far.
755
 */
756
int ssl3_take_mac(SSL_CONNECTION *s)
757
0
{
758
0
    const char *sender;
759
0
    size_t slen;
760
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
761
762
0
    if (!s->server) {
763
0
        sender = ssl->method->ssl3_enc->server_finished_label;
764
0
        slen = ssl->method->ssl3_enc->server_finished_label_len;
765
0
    } else {
766
0
        sender = ssl->method->ssl3_enc->client_finished_label;
767
0
        slen = ssl->method->ssl3_enc->client_finished_label_len;
768
0
    }
769
770
0
    s->s3.tmp.peer_finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
771
0
        s->s3.tmp.peer_finish_md);
772
773
0
    if (s->s3.tmp.peer_finish_md_len == 0) {
774
        /* SSLfatal() already called */
775
0
        return 0;
776
0
    }
777
778
0
    return 1;
779
0
}
780
781
MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
782
    PACKET *pkt)
783
0
{
784
0
    size_t remain;
785
786
0
    remain = PACKET_remaining(pkt);
787
    /*
788
     * 'Change Cipher Spec' is just a single byte, which should already have
789
     * been consumed by ssl_get_message() so there should be no bytes left,
790
     * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
791
     */
792
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
793
0
        if ((s->version == DTLS1_BAD_VER
794
0
                && remain != DTLS1_CCS_HEADER_LENGTH + 1)
795
0
            || (s->version != DTLS1_BAD_VER
796
0
                && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
797
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
798
0
            return MSG_PROCESS_ERROR;
799
0
        }
800
0
    } else {
801
0
        if (remain != 0) {
802
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
803
0
            return MSG_PROCESS_ERROR;
804
0
        }
805
0
    }
806
807
    /* Check we have a cipher to change to */
808
0
    if (s->s3.tmp.new_cipher == NULL) {
809
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
810
0
        return MSG_PROCESS_ERROR;
811
0
    }
812
813
0
    s->s3.change_cipher_spec = 1;
814
0
    if (!ssl3_do_change_cipher_spec(s)) {
815
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
816
0
        return MSG_PROCESS_ERROR;
817
0
    }
818
819
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
820
0
        if (s->version == DTLS1_BAD_VER)
821
0
            s->d1->handshake_read_seq++;
822
823
#ifndef OPENSSL_NO_SCTP
824
        /*
825
         * Remember that a CCS has been received, so that an old key of
826
         * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
827
         * SCTP is used
828
         */
829
        BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
830
            BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
831
#endif
832
0
    }
833
834
0
    return MSG_PROCESS_CONTINUE_READING;
835
0
}
836
837
MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
838
0
{
839
0
    size_t md_len;
840
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
841
0
    int was_first = SSL_IS_FIRST_HANDSHAKE(s);
842
0
    int ok;
843
844
    /*
845
     * A DTLS 1.3 Finished is protected with the peer's handshake keys. If we
846
     * have not installed them yet we have no key to verify it with either.
847
     */
848
0
    if (SSL_CONNECTION_IS_DTLS13(s) && dtls1_get_epoch(s, SSL3_CC_READ) < 2) {
849
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
850
0
        return MSG_PROCESS_ERROR;
851
0
    }
852
853
    /* This is a real handshake so make sure we clean it up at the end */
854
0
    if (s->server) {
855
        /*
856
         * To get this far we must have read encrypted data from the client. We
857
         * no longer tolerate unencrypted alerts. This is ignored if less than
858
         * (D)TLSv1.3
859
         */
860
0
        if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
861
0
            s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
862
0
        if (s->post_handshake_auth != SSL_PHA_REQUESTED)
863
0
            s->statem.cleanuphand = 1;
864
0
        if (SSL_CONNECTION_IS_VERSION13(s)
865
0
            && !tls13_save_handshake_digest_for_pha(s)) {
866
            /* SSLfatal() already called */
867
0
            return MSG_PROCESS_ERROR;
868
0
        }
869
0
    }
870
871
    /*
872
     * In TLSv1.3 a Finished message signals a key change so the end of the
873
     * message must be on a record boundary.
874
     */
875
0
    if (SSL_CONNECTION_IS_VERSION13(s)
876
0
        && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
877
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
878
0
        return MSG_PROCESS_ERROR;
879
0
    }
880
881
    /* If this occurs, we have missed a message */
882
0
    if (!SSL_CONNECTION_IS_VERSION13(s) && !s->s3.change_cipher_spec) {
883
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
884
0
        return MSG_PROCESS_ERROR;
885
0
    }
886
0
    s->s3.change_cipher_spec = 0;
887
888
0
    md_len = s->s3.tmp.peer_finish_md_len;
889
890
0
    if (md_len != PACKET_remaining(pkt)) {
891
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
892
0
        return MSG_PROCESS_ERROR;
893
0
    }
894
895
0
    ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
896
0
        md_len);
897
0
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
898
0
    if (ok != 0) {
899
0
        if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
900
0
            ok = 0;
901
0
        }
902
0
    }
903
0
#endif
904
0
    if (ok != 0) {
905
0
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
906
0
        return MSG_PROCESS_ERROR;
907
0
    }
908
909
    /*
910
     * Copy the finished so we can use it for renegotiation checks
911
     */
912
0
    if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
913
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
914
0
        return MSG_PROCESS_ERROR;
915
0
    }
916
0
    if (s->server) {
917
0
        memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
918
0
            md_len);
919
0
        s->s3.previous_client_finished_len = md_len;
920
0
    } else {
921
0
        memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
922
0
            md_len);
923
0
        s->s3.previous_server_finished_len = md_len;
924
0
    }
925
926
    /*
927
     * In TLS1.3 we also have to change cipher state and do any final processing
928
     * of the initial server flight (if we are a client)
929
     */
930
0
    if (SSL_CONNECTION_IS_VERSION13(s)) {
931
0
        if (s->server) {
932
0
            if (s->post_handshake_auth != SSL_PHA_REQUESTED && !ssl->method->ssl3_enc->change_cipher_state(s, SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_READ)) {
933
                /* SSLfatal() already called */
934
0
                return MSG_PROCESS_ERROR;
935
0
            }
936
0
        } else {
937
            /* (D)TLS 1.3 gets the secret size from the handshake md */
938
0
            size_t dummy;
939
0
            if (!ssl->method->ssl3_enc->generate_master_secret(s,
940
0
                    s->master_secret, s->handshake_secret, 0,
941
0
                    &dummy)) {
942
                /* SSLfatal() already called */
943
0
                return MSG_PROCESS_ERROR;
944
0
            }
945
0
            if (!tls13_store_server_finished_hash(s)) {
946
                /* SSLfatal() already called */
947
0
                return MSG_PROCESS_ERROR;
948
0
            }
949
950
            /*
951
             * For non-QUIC we set up the client's app data read keys now, so
952
             * that we can go straight into reading 0.5RTT data from the server.
953
             * For QUIC we don't do that, and instead defer setting up the keys
954
             * until after we have set up the write keys in order to ensure that
955
             * write keys are always set up before read keys (so that if we read
956
             * a message we have the correct keys in place to ack it)
957
             */
958
0
            if (!SSL_IS_QUIC_HANDSHAKE(s)
959
0
                && !ssl->method->ssl3_enc->change_cipher_state(s,
960
0
                    SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
961
                /* SSLfatal() already called */
962
0
                return MSG_PROCESS_ERROR;
963
0
            }
964
0
            if (!tls_process_initial_server_flight(s)) {
965
                /* SSLfatal() already called */
966
0
                return MSG_PROCESS_ERROR;
967
0
            }
968
0
        }
969
0
    }
970
971
0
    if (was_first
972
0
        && !SSL_IS_FIRST_HANDSHAKE(s)
973
0
        && s->rlayer.rrlmethod->set_first_handshake != NULL)
974
0
        s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
975
976
0
    return MSG_PROCESS_FINISHED_READING;
977
0
}
978
979
CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
980
0
{
981
0
    if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
982
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
983
0
        return CON_FUNC_ERROR;
984
0
    }
985
986
0
    return CON_FUNC_SUCCESS;
987
0
}
988
989
/* Add a certificate to the WPACKET */
990
static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
991
    X509 *x, int chain, int for_comp)
992
0
{
993
0
    int len;
994
0
    unsigned char *outbytes;
995
0
    int context = SSL_EXT_TLS1_3_CERTIFICATE;
996
997
0
    if (for_comp)
998
0
        context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
999
1000
0
    len = i2d_X509(x, NULL);
1001
0
    if (len < 0) {
1002
0
        if (!for_comp)
1003
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
1004
0
        return 0;
1005
0
    }
1006
0
    if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
1007
0
        || i2d_X509(x, &outbytes) != len) {
1008
0
        if (!for_comp)
1009
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1010
0
        return 0;
1011
0
    }
1012
1013
0
    if ((SSL_CONNECTION_IS_VERSION13(s) || for_comp)
1014
0
        && !tls_construct_extensions(s, pkt, context, x, chain)) {
1015
        /* SSLfatal() already called */
1016
0
        return 0;
1017
0
    }
1018
1019
0
    return 1;
1020
0
}
1021
1022
/* Add certificate chain to provided WPACKET */
1023
static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
1024
0
{
1025
0
    int i, chain_count;
1026
0
    X509 *x;
1027
0
    STACK_OF(X509) *extra_certs;
1028
0
    STACK_OF(X509) *chain = NULL;
1029
0
    X509_STORE *chain_store;
1030
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1031
1032
0
    if (cpk == NULL || cpk->x509 == NULL)
1033
0
        return 1;
1034
1035
0
    x = cpk->x509;
1036
1037
    /*
1038
     * If we have a certificate specific chain use it, else use parent ctx.
1039
     */
1040
0
    if (cpk->chain != NULL)
1041
0
        extra_certs = cpk->chain;
1042
0
    else
1043
0
        extra_certs = sctx->extra_certs;
1044
1045
0
    if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1046
0
        chain_store = NULL;
1047
0
    else if (s->cert->chain_store)
1048
0
        chain_store = s->cert->chain_store;
1049
0
    else
1050
0
        chain_store = sctx->cert_store;
1051
1052
0
    if (chain_store != NULL) {
1053
0
        X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
1054
0
            sctx->propq);
1055
1056
0
        if (xs_ctx == NULL) {
1057
0
            if (!for_comp)
1058
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1059
0
            return 0;
1060
0
        }
1061
0
        if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1062
0
            X509_STORE_CTX_free(xs_ctx);
1063
0
            if (!for_comp)
1064
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1065
0
            return 0;
1066
0
        }
1067
        /*
1068
         * It is valid for the chain not to be complete (because normally we
1069
         * don't include the root cert in the chain). Therefore we deliberately
1070
         * ignore the error return from this call. We're not actually verifying
1071
         * the cert - we're just building as much of the chain as we can
1072
         */
1073
0
        (void)X509_verify_cert(xs_ctx);
1074
        /* Don't leave errors in the queue */
1075
0
        ERR_clear_error();
1076
0
        chain = X509_STORE_CTX_get0_chain(xs_ctx);
1077
0
        i = ssl_security_cert_chain(s, chain, NULL);
1078
0
        if (i != 1) {
1079
#if 0
1080
            /* Dummy error calls so mkerr generates them */
1081
            ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1082
            ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1083
            ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1084
#endif
1085
0
            X509_STORE_CTX_free(xs_ctx);
1086
0
            if (!for_comp)
1087
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1088
0
            return 0;
1089
0
        }
1090
0
        chain_count = sk_X509_num(chain);
1091
0
        for (i = 0; i < chain_count; i++) {
1092
0
            x = sk_X509_value(chain, i);
1093
1094
0
            if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1095
                /* SSLfatal() already called */
1096
0
                X509_STORE_CTX_free(xs_ctx);
1097
0
                return 0;
1098
0
            }
1099
0
        }
1100
0
        X509_STORE_CTX_free(xs_ctx);
1101
0
    } else {
1102
0
        i = ssl_security_cert_chain(s, extra_certs, x);
1103
0
        if (i != 1) {
1104
0
            if (!for_comp)
1105
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1106
0
            return 0;
1107
0
        }
1108
0
        if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1109
            /* SSLfatal() already called */
1110
0
            return 0;
1111
0
        }
1112
0
        for (i = 0; i < sk_X509_num(extra_certs); i++) {
1113
0
            x = sk_X509_value(extra_certs, i);
1114
0
            if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1115
                /* SSLfatal() already called */
1116
0
                return 0;
1117
0
            }
1118
0
        }
1119
0
    }
1120
0
    return 1;
1121
0
}
1122
1123
EVP_PKEY *tls_get_peer_pkey(const SSL_CONNECTION *sc)
1124
0
{
1125
0
    if (sc->session->peer_rpk != NULL)
1126
0
        return sc->session->peer_rpk;
1127
0
    if (sc->session->peer != NULL)
1128
0
        return X509_get0_pubkey(sc->session->peer);
1129
0
    return NULL;
1130
0
}
1131
1132
int tls_process_rpk(SSL_CONNECTION *sc, PACKET *pkt, EVP_PKEY **peer_rpk)
1133
0
{
1134
0
    EVP_PKEY *pkey = NULL;
1135
0
    int ret = 0;
1136
0
    RAW_EXTENSION *rawexts = NULL;
1137
0
    PACKET extensions;
1138
0
    PACKET context;
1139
0
    unsigned long cert_len = 0, spki_len = 0;
1140
0
    const unsigned char *spki, *spkistart;
1141
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
1142
1143
    /*-
1144
     * ----------------------------
1145
     * (D)TLS 1.3 Certificate message:
1146
     * ----------------------------
1147
     * https://datatracker.ietf.org/doc/html/rfc9846#section-4.5.1
1148
     *
1149
     *   enum {
1150
     *       X509(0),
1151
     *       RawPublicKey(2),
1152
     *       (255)
1153
     *   } CertificateType;
1154
     *
1155
     *   struct {
1156
     *       select (certificate_type) {
1157
     *           case RawPublicKey:
1158
     *             // From RFC 7250 ASN.1_subjectPublicKeyInfo
1159
     *             opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
1160
     *
1161
     *           case X509:
1162
     *             opaque cert_data<1..2^24-1>;
1163
     *       };
1164
     *       Extension extensions<0..2^16-1>;
1165
     *   } CertificateEntry;
1166
     *
1167
     *   struct {
1168
     *       opaque certificate_request_context<0..2^8-1>;
1169
     *       CertificateEntry certificate_list<0..2^24-1>;
1170
     *   } Certificate;
1171
     *
1172
     * The client MUST send a Certificate message if and only if the server
1173
     * has requested client authentication via a CertificateRequest message
1174
     * (Section 4.3.2).  If the server requests client authentication but no
1175
     * suitable certificate is available, the client MUST send a Certificate
1176
     * message containing no certificates (i.e., with the "certificate_list"
1177
     * field having length 0).
1178
     *
1179
     * ----------------------------
1180
     * TLS 1.2 Certificate message:
1181
     * ----------------------------
1182
     * https://datatracker.ietf.org/doc/html/rfc7250#section-3
1183
     *
1184
     *   opaque ASN.1Cert<1..2^24-1>;
1185
     *
1186
     *   struct {
1187
     *       select(certificate_type){
1188
     *
1189
     *            // certificate type defined in this document.
1190
     *            case RawPublicKey:
1191
     *              opaque ASN.1_subjectPublicKeyInfo<1..2^24-1>;
1192
     *
1193
     *           // X.509 certificate defined in RFC 5246
1194
     *           case X.509:
1195
     *             ASN.1Cert certificate_list<0..2^24-1>;
1196
     *
1197
     *           // Additional certificate type based on
1198
     *           // "TLS Certificate Types" subregistry
1199
     *       };
1200
     *   } Certificate;
1201
     *
1202
     * -------------
1203
     * Consequently:
1204
     * -------------
1205
     * After the ((D)TLS 1.3 only) context octet string (1 byte length + data) the
1206
     * Certificate message has a 3-byte length that is zero in the client to
1207
     * server message when the client has no RPK to send.  In that case, there
1208
     * are no ((D)TLS 1.3 only) per-certificate extensions either, because the
1209
     * [CertificateEntry] list is empty.
1210
     *
1211
     * In the server to client direction, or when the client had an RPK to send,
1212
     * the (D)TLS 1.3 message just prepends the length of the RPK+extensions,
1213
     * while TLS <= 1.2 sends just the RPK (octet-string).
1214
     *
1215
     * The context must be zero-length in the server to client direction, and
1216
     * must match the value recorded in the certificate request in the client
1217
     * to server direction.
1218
     */
1219
0
    if (SSL_CONNECTION_IS_VERSION13(sc)) {
1220
0
        if (!PACKET_get_length_prefixed_1(pkt, &context)) {
1221
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1222
0
            goto err;
1223
0
        }
1224
0
        if (sc->server) {
1225
0
            if (sc->pha_context == NULL) {
1226
0
                if (PACKET_remaining(&context) != 0) {
1227
0
                    SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1228
0
                    goto err;
1229
0
                }
1230
0
            } else {
1231
0
                if (!PACKET_equal(&context, sc->pha_context, sc->pha_context_len)) {
1232
0
                    SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1233
0
                    goto err;
1234
0
                }
1235
0
            }
1236
0
        } else {
1237
0
            if (PACKET_remaining(&context) != 0) {
1238
0
                SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1239
0
                goto err;
1240
0
            }
1241
0
        }
1242
0
    }
1243
1244
0
    if (!PACKET_get_net_3(pkt, &cert_len)
1245
0
        || PACKET_remaining(pkt) != cert_len) {
1246
0
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1247
0
        goto err;
1248
0
    }
1249
1250
    /*
1251
     * The list length may be zero when there is no RPK.  In the case of TLS
1252
     * 1.2 this is actually the RPK length, which cannot be zero as specified,
1253
     * but that breaks the ability of the client to decline client auth. We
1254
     * overload the 0 RPK length to mean "no RPK".  This interpretation is
1255
     * also used some other (reference?) implementations, but is not supported
1256
     * by the verbatim RFC7250 text.
1257
     */
1258
0
    if (cert_len == 0)
1259
0
        return 1;
1260
1261
0
    if (SSL_CONNECTION_IS_VERSION13(sc)) {
1262
        /*
1263
         * With TLS 1.3, a non-empty explicit-length RPK octet-string followed
1264
         * by a possibly empty extension block.
1265
         */
1266
0
        if (!PACKET_get_net_3(pkt, &spki_len)) {
1267
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1268
0
            goto err;
1269
0
        }
1270
0
        if (spki_len == 0) {
1271
            /* empty RPK */
1272
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_EMPTY_RAW_PUBLIC_KEY);
1273
0
            goto err;
1274
0
        }
1275
0
    } else {
1276
0
        spki_len = cert_len;
1277
0
    }
1278
1279
0
    if (!PACKET_get_bytes(pkt, &spki, spki_len)) {
1280
0
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1281
0
        goto err;
1282
0
    }
1283
0
    spkistart = spki;
1284
0
    if ((pkey = d2i_PUBKEY_ex(NULL, &spki, spki_len, sctx->libctx, sctx->propq)) == NULL
1285
0
        || spki != (spkistart + spki_len)) {
1286
0
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1287
0
        goto err;
1288
0
    }
1289
0
    if (EVP_PKEY_missing_parameters(pkey)) {
1290
0
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR,
1291
0
            SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1292
0
        goto err;
1293
0
    }
1294
1295
    /* Process the Extensions block */
1296
0
    if (SSL_CONNECTION_IS_VERSION13(sc)) {
1297
0
        if (PACKET_remaining(pkt) != (cert_len - 3 - spki_len)) {
1298
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1299
0
            goto err;
1300
0
        }
1301
0
        if (!PACKET_as_length_prefixed_2(pkt, &extensions)
1302
0
            || PACKET_remaining(pkt) != 0) {
1303
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1304
0
            goto err;
1305
0
        }
1306
0
        if (!tls_collect_extensions(sc, &extensions, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1307
0
                &rawexts, NULL, 1)) {
1308
            /* SSLfatal already called */
1309
0
            goto err;
1310
0
        }
1311
        /* chain index is always zero and fin always 1 for RPK */
1312
0
        if (!tls_parse_all_extensions(sc, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1313
0
                rawexts, NULL, 0, 1)) {
1314
            /* SSLfatal already called */
1315
0
            goto err;
1316
0
        }
1317
0
    }
1318
0
    ret = 1;
1319
0
    if (peer_rpk != NULL) {
1320
0
        *peer_rpk = pkey;
1321
0
        pkey = NULL;
1322
0
    }
1323
1324
0
err:
1325
0
    OPENSSL_free(rawexts);
1326
0
    EVP_PKEY_free(pkey);
1327
0
    return ret;
1328
0
}
1329
1330
unsigned long tls_output_rpk(SSL_CONNECTION *sc, WPACKET *pkt, CERT_PKEY *cpk)
1331
0
{
1332
0
    int pdata_len = 0;
1333
0
    unsigned char *pdata = NULL;
1334
0
    const X509_PUBKEY *xpk = NULL;
1335
0
    unsigned long ret = 0;
1336
0
    X509 *x509 = NULL;
1337
1338
0
    if (cpk != NULL && cpk->x509 != NULL) {
1339
0
        x509 = cpk->x509;
1340
        /* Get the RPK from the certificate */
1341
0
        xpk = X509_get_X509_PUBKEY(cpk->x509);
1342
0
        if (xpk == NULL) {
1343
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1344
0
            goto err;
1345
0
        }
1346
0
        pdata_len = i2d_X509_PUBKEY(xpk, &pdata);
1347
0
    } else if (cpk != NULL && cpk->privatekey != NULL) {
1348
        /* Get the RPK from the private key */
1349
0
        pdata_len = i2d_PUBKEY(cpk->privatekey, &pdata);
1350
0
    } else {
1351
        /* The server RPK is not optional */
1352
0
        if (sc->server) {
1353
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1354
0
            goto err;
1355
0
        }
1356
        /* The client can send a zero length certificate list */
1357
0
        if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1358
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1359
0
            goto err;
1360
0
        }
1361
0
        return 1;
1362
0
    }
1363
1364
0
    if (pdata_len <= 0) {
1365
0
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1366
0
        goto err;
1367
0
    }
1368
1369
    /*
1370
     * TLSv1.2 is _just_ the raw public key
1371
     * TLSv1.3 includes extensions, so there's a length wrapper
1372
     */
1373
0
    if (SSL_CONNECTION_IS_VERSION13(sc)) {
1374
0
        if (!WPACKET_start_sub_packet_u24(pkt)) {
1375
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1376
0
            goto err;
1377
0
        }
1378
0
    }
1379
1380
0
    if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1381
0
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1382
0
        goto err;
1383
0
    }
1384
1385
0
    if (SSL_CONNECTION_IS_VERSION13(sc)) {
1386
        /*
1387
         * Only send extensions relevant to raw public keys. Until such
1388
         * extensions are defined, this will be an empty set of extensions.
1389
         * |x509| may be NULL, which raw public-key extensions need to handle.
1390
         */
1391
0
        if (!tls_construct_extensions(sc, pkt, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1392
0
                x509, 0)) {
1393
            /* SSLfatal() already called */
1394
0
            goto err;
1395
0
        }
1396
0
        if (!WPACKET_close(pkt)) {
1397
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1398
0
            goto err;
1399
0
        }
1400
0
    }
1401
1402
0
    ret = 1;
1403
0
err:
1404
0
    OPENSSL_free(pdata);
1405
0
    return ret;
1406
0
}
1407
1408
unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1409
    CERT_PKEY *cpk, int for_comp)
1410
0
{
1411
0
    if (!WPACKET_start_sub_packet_u24(pkt)) {
1412
0
        if (!for_comp)
1413
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1414
0
        return 0;
1415
0
    }
1416
1417
0
    if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1418
0
        return 0;
1419
1420
0
    if (!WPACKET_close(pkt)) {
1421
0
        if (!for_comp)
1422
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1423
0
        return 0;
1424
0
    }
1425
1426
0
    return 1;
1427
0
}
1428
1429
/*
1430
 * Tidy up after the end of a handshake. In the case of SCTP this may result
1431
 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1432
 * freed up as well.
1433
 */
1434
WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1435
    int clearbufs, int stop)
1436
0
{
1437
0
    void (*cb)(const SSL *ssl, int type, int val) = NULL;
1438
0
    int cleanuphand = s->statem.cleanuphand;
1439
0
    SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
1440
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1441
1442
0
    if (clearbufs) {
1443
0
        if (!SSL_CONNECTION_IS_DTLS(s)
1444
#ifndef OPENSSL_NO_SCTP
1445
            /*
1446
             * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1447
             * messages that require it. Therefore, DTLS procedures for retransmissions
1448
             * MUST NOT be used.
1449
             * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1450
             */
1451
            || BIO_dgram_is_sctp(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)))
1452
#endif
1453
0
        ) {
1454
            /*
1455
             * We don't do this in DTLS over UDP because we may still need the init_buf
1456
             * in case there are any unexpected retransmits
1457
             */
1458
0
            BUF_MEM_free(s->init_buf);
1459
0
            s->init_buf = NULL;
1460
0
        }
1461
1462
0
        if (!ssl_free_wbio_buffer(s)) {
1463
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1464
0
            return WORK_ERROR;
1465
0
        }
1466
0
        s->init_num = 0;
1467
0
    }
1468
1469
0
    if (SSL_CONNECTION_IS_VERSION13(s) && !s->server
1470
0
        && s->post_handshake_auth == SSL_PHA_REQUESTED)
1471
0
        s->post_handshake_auth = SSL_PHA_EXT_SENT;
1472
1473
    /*
1474
     * Only set if there was a Finished message and this isn't after a TLSv1.3
1475
     * post handshake exchange
1476
     */
1477
0
    if (cleanuphand) {
1478
        /* skipped if we just sent a HelloRequest */
1479
0
        s->renegotiate = 0;
1480
0
        s->new_session = 0;
1481
0
        s->statem.cleanuphand = 0;
1482
0
        s->ext.ticket_expected = 0;
1483
1484
0
        ssl3_cleanup_key_block(s);
1485
1486
0
        if (s->server) {
1487
            /*
1488
             * In TLSv1.3 we update the cache as part of constructing the
1489
             * NewSessionTicket
1490
             */
1491
0
            if (!SSL_CONNECTION_IS_VERSION13(s))
1492
0
                ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1493
1494
            /* N.B. s->ctx may not equal s->session_ctx */
1495
0
            ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1496
0
            s->handshake_func = ossl_statem_accept;
1497
0
        } else {
1498
0
            if (SSL_CONNECTION_IS_VERSION13(s)) {
1499
                /*
1500
                 * We encourage applications to only use TLSv1.3 tickets once,
1501
                 * so we remove this one from the cache.
1502
                 */
1503
0
                if ((s->session_ctx->session_cache_mode
1504
0
                        & SSL_SESS_CACHE_CLIENT)
1505
0
                    != 0)
1506
0
                    SSL_CTX_remove_session(s->session_ctx, s->session);
1507
0
            } else {
1508
                /*
1509
                 * In TLSv1.3 we update the cache as part of processing the
1510
                 * NewSessionTicket
1511
                 */
1512
0
                ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1513
0
            }
1514
0
            if (s->hit)
1515
0
                ssl_tsan_counter(s->session_ctx,
1516
0
                    &s->session_ctx->stats.sess_hit);
1517
1518
0
            s->handshake_func = ossl_statem_connect;
1519
0
            ssl_tsan_counter(s->session_ctx,
1520
0
                &s->session_ctx->stats.sess_connect_good);
1521
0
        }
1522
1523
0
        if (SSL_CONNECTION_IS_DTLS(s)) {
1524
            /* done with handshaking */
1525
            /*
1526
             * In DTLS 1.3, we must not reset the handshake sequence numbers
1527
             * because post-handshake messages like NewSessionTicket need to
1528
             * continue the sequence numbering from where the handshake left off.
1529
             */
1530
0
            if (!SSL_CONNECTION_IS_DTLS13(s)) {
1531
0
                s->d1->handshake_read_seq = 0;
1532
0
                s->d1->handshake_write_seq = 0;
1533
0
                s->d1->next_handshake_write_seq = 0;
1534
0
            }
1535
0
            dtls1_clear_received_buffer(s);
1536
0
        }
1537
0
    }
1538
1539
0
    if (s->info_callback != NULL)
1540
0
        cb = s->info_callback;
1541
0
    else if (sctx->info_callback != NULL)
1542
0
        cb = sctx->info_callback;
1543
1544
    /*
1545
     * The callback may expect us to not be in init at handshake done --
1546
     * but not for DTLS1.3 if a KeyUpdate is still scheduled and hasn't
1547
     * been constructed yet (e.g. a reciprocal one scheduled by
1548
     * tls_process_key_update() while processing the very message whose
1549
     * completion brought us here): clearing in_init here would mean
1550
     * nothing ever tells a later SSL_write()/SSL_do_handshake() call to
1551
     * re-enter the state machine and actually send it.
1552
     */
1553
0
    if (!SSL_CONNECTION_IS_DTLS13(s) || s->key_update == SSL_KEY_UPDATE_NONE)
1554
0
        ossl_statem_set_in_init(s, 0);
1555
1556
0
    if (cb != NULL) {
1557
0
        if (cleanuphand
1558
0
            || !SSL_CONNECTION_IS_VERSION13(s)
1559
0
            || SSL_IS_FIRST_HANDSHAKE(s))
1560
0
            cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1561
0
    }
1562
1563
0
    if (!stop) {
1564
        /* If we've got more work to do we go back into init */
1565
0
        ossl_statem_set_in_init(s, 1);
1566
0
        return WORK_FINISHED_CONTINUE;
1567
0
    }
1568
1569
0
    return WORK_FINISHED_STOP;
1570
0
}
1571
1572
/*
1573
 * TLS 1.3 reserves handshake message type 0, so a HelloRequest must reach the
1574
 * state machine and be rejected there whenever TLS 1.3 is still possible.
1575
 *
1576
 * By the time a client reads a server handshake message, s->version is either
1577
 * the configured maximum for an initial pre-ServerHello handshake, or the
1578
 * already negotiated version after ServerHello or during renegotiation. Skip
1579
 * only when that version is below TLS 1.3.
1580
 */
1581
static int should_skip_hello_request(const SSL_CONNECTION *s)
1582
0
{
1583
0
    if (SSL_CONNECTION_IS_TLS13(s))
1584
0
        return 0;
1585
1586
0
    return s->version > 0 && s->version < TLS1_3_VERSION;
1587
0
}
1588
1589
int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1590
0
{
1591
    /* s->init_num < SSL3_HM_HEADER_LENGTH */
1592
0
    int skip_message, i;
1593
0
    uint8_t recvd_type;
1594
0
    unsigned char *p;
1595
0
    size_t l, readbytes;
1596
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1597
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1598
1599
0
    p = (unsigned char *)s->init_buf->data;
1600
1601
0
    do {
1602
0
        while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1603
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1604
0
                &p[s->init_num],
1605
0
                SSL3_HM_HEADER_LENGTH - s->init_num,
1606
0
                0, &readbytes);
1607
0
            if (i <= 0) {
1608
0
                s->rwstate = SSL_READING;
1609
0
                return 0;
1610
0
            }
1611
0
            if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1612
                /*
1613
                 * A ChangeCipherSpec must be a single byte and may not occur
1614
                 * in the middle of a handshake message.
1615
                 */
1616
0
                if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1617
0
                    SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1618
0
                        SSL_R_BAD_CHANGE_CIPHER_SPEC);
1619
0
                    return 0;
1620
0
                }
1621
0
                if (s->statem.hand_state == TLS_ST_BEFORE
1622
0
                    && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1623
                    /*
1624
                     * We are stateless and we received a CCS. Probably this is
1625
                     * from a client between the first and second ClientHellos.
1626
                     * We should ignore this, but return an error because we do
1627
                     * not return success until we see the second ClientHello
1628
                     * with a valid cookie.
1629
                     */
1630
0
                    return 0;
1631
0
                }
1632
0
                s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1633
0
                s->init_num = readbytes - 1;
1634
0
                s->init_msg = s->init_buf->data;
1635
0
                s->s3.tmp.message_size = readbytes;
1636
0
                return 1;
1637
0
            } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1638
0
                SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1639
0
                    SSL_R_CCS_RECEIVED_EARLY);
1640
0
                return 0;
1641
0
            }
1642
0
            s->init_num += readbytes;
1643
0
        }
1644
1645
0
        skip_message = 0;
1646
0
        if (!s->server)
1647
0
            if (s->statem.hand_state != TLS_ST_OK
1648
0
                && p[0] == SSL3_MT_HELLO_REQUEST
1649
0
                && should_skip_hello_request(s))
1650
                /*
1651
                 * The server may always send 'Hello Request' messages --
1652
                 * we are doing a handshake anyway now, so ignore them if
1653
                 * their format is correct. Does not count for 'Finished'
1654
                 * MAC.
1655
                 */
1656
0
                if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1657
0
                    s->init_num = 0;
1658
0
                    skip_message = 1;
1659
1660
0
                    if (s->msg_callback)
1661
0
                        s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1662
0
                            p, SSL3_HM_HEADER_LENGTH, ussl,
1663
0
                            s->msg_callback_arg);
1664
0
                }
1665
0
    } while (skip_message);
1666
    /* s->init_num == SSL3_HM_HEADER_LENGTH */
1667
1668
0
    *mt = *p;
1669
0
    s->s3.tmp.message_type = *(p++);
1670
1671
0
    n2l3(p, l);
1672
    /* BUF_MEM_grow takes an 'int' parameter */
1673
0
    if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1674
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1675
0
        return 0;
1676
0
    }
1677
0
    s->s3.tmp.message_size = l;
1678
1679
0
    s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1680
0
    s->init_num = 0;
1681
1682
0
    return 1;
1683
0
}
1684
1685
static int grow_init_buf(SSL_CONNECTION *s, size_t size)
1686
0
{
1687
1688
0
    size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
1689
1690
0
    if (!BUF_MEM_grow_clean(s->init_buf, size))
1691
0
        return 0;
1692
1693
0
    if (size < msg_offset)
1694
0
        return 0;
1695
1696
0
    s->init_msg = s->init_buf->data + msg_offset;
1697
1698
0
    return 1;
1699
0
}
1700
1701
int tls_common_finish_mac(SSL_CONNECTION *s)
1702
0
{
1703
0
    unsigned char *msg = (unsigned char *)s->init_buf->data;
1704
0
    size_t msg_len = s->init_num;
1705
0
    size_t hdr_len = 0;
1706
1707
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
1708
0
        if (s->version != DTLS1_BAD_VER)
1709
0
            hdr_len = DTLS1_HM_HEADER_LENGTH;
1710
0
        else
1711
0
            msg += DTLS1_HM_HEADER_LENGTH;
1712
0
    } else {
1713
0
        hdr_len = SSL3_HM_HEADER_LENGTH;
1714
0
    }
1715
1716
0
    msg_len += hdr_len;
1717
1718
    /* Feed this message into MAC computation. */
1719
1720
    /*
1721
     * We defer feeding in the HRR until later. We'll do it as part of
1722
     * the message processing.
1723
     * The (D)TLSv1.3 handshake transcript stops at the ClientFinished
1724
     * message.
1725
     */
1726
0
    const size_t srvhellorandom_offs = hdr_len + 2;
1727
1728
    /* KeyUpdate and NewSessionTicket do not need to be added */
1729
0
    if (!SSL_CONNECTION_IS_VERSION13(s)
1730
0
        || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1731
0
            && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1732
0
        if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1733
0
            || s->init_num < srvhellorandom_offs + SSL3_RANDOM_SIZE
1734
0
            || memcmp(hrrrandom,
1735
0
                   s->init_buf->data + srvhellorandom_offs,
1736
0
                   SSL3_RANDOM_SIZE)
1737
0
                != 0) {
1738
0
            if (!ssl3_finish_mac(s, msg, msg_len))
1739
                /* SSLfatal() already called */
1740
0
                return 0;
1741
0
        }
1742
0
    }
1743
1744
0
    return 1;
1745
0
}
1746
1747
int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1748
0
{
1749
0
    size_t toread, readbytes;
1750
0
    unsigned char *p;
1751
0
    int i;
1752
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1753
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1754
1755
0
    if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1756
        /* We've already read everything in */
1757
0
        *len = (unsigned long)s->init_num;
1758
0
        return 1;
1759
0
    }
1760
1761
0
    toread = s->s3.tmp.message_size - s->init_num;
1762
0
    while (toread > 0) {
1763
0
        size_t chunk = toread > SSL3_RT_MAX_PLAIN_LENGTH ? SSL3_RT_MAX_PLAIN_LENGTH : toread;
1764
1765
        /*
1766
         * We incrementally allocate the buffer to guard against the peer
1767
         * claiming a very large message size and then not sending it.
1768
         */
1769
0
        if (!grow_init_buf(s, s->init_num + chunk + SSL3_HM_HEADER_LENGTH)) {
1770
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
1771
0
            return 0;
1772
0
        }
1773
1774
        /* init_msg location can change after grow_init_buf */
1775
0
        p = s->init_msg;
1776
0
        i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1777
0
            &p[s->init_num], chunk, 0, &readbytes);
1778
0
        if (i <= 0) {
1779
0
            s->rwstate = SSL_READING;
1780
0
            *len = 0;
1781
0
            return 0;
1782
0
        }
1783
0
        s->init_num += readbytes;
1784
0
        toread -= readbytes;
1785
0
    }
1786
1787
    /*
1788
     * If receiving Finished, record MAC of prior handshake messages for
1789
     * Finished verification.
1790
     */
1791
0
    if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1792
        /* SSLfatal() already called */
1793
0
        *len = 0;
1794
0
        return 0;
1795
0
    }
1796
1797
0
    if (!tls_common_finish_mac(s)) {
1798
        /* SSLfatal() already called */
1799
0
        *len = 0;
1800
0
        return 0;
1801
0
    }
1802
1803
0
    if (s->msg_callback)
1804
0
        s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1805
0
            (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ussl,
1806
0
            s->msg_callback_arg);
1807
1808
0
    *len = s->init_num;
1809
0
    return 1;
1810
0
}
1811
1812
static const X509ERR2ALERT x509table[] = {
1813
    { X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE },
1814
    { X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE },
1815
    { X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE },
1816
    { X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE },
1817
    { X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA },
1818
    { X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED },
1819
    { X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE },
1820
    { X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE },
1821
    { X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED },
1822
    { X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR },
1823
    { X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE },
1824
    { X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED },
1825
    { X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE },
1826
    { X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR },
1827
    { X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE },
1828
    { X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA },
1829
    { X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE },
1830
    { X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE },
1831
    { X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE },
1832
    { X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE },
1833
    { X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE },
1834
    { X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE },
1835
    { X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE },
1836
    { X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA },
1837
    { X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR },
1838
    { X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE },
1839
    { X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE },
1840
    { X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR },
1841
    { X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA },
1842
    { X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA },
1843
    { X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR },
1844
    { X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE },
1845
    { X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE },
1846
    { X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE },
1847
    { X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA },
1848
    { X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA },
1849
    { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA },
1850
    { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA },
1851
    { X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA },
1852
    { X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR },
1853
1854
    /* Last entry; return this if we don't find the value above. */
1855
    { X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN }
1856
};
1857
1858
int ssl_x509err2alert(int x509err)
1859
0
{
1860
0
    const X509ERR2ALERT *tp;
1861
1862
0
    for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1863
0
        if (tp->x509err == x509err)
1864
0
            break;
1865
0
    return tp->alert;
1866
0
}
1867
1868
int ssl_allow_compression(SSL_CONNECTION *s)
1869
0
{
1870
0
    if (s->options & SSL_OP_NO_COMPRESSION)
1871
0
        return 0;
1872
0
    return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1873
0
}
1874
1875
/*
1876
 * SSL/TLS/DTLS version comparison
1877
 *
1878
 * Returns
1879
 *      0 if versiona is equal to versionb
1880
 *      1 if versiona is greater than versionb
1881
 *     -1 if versiona is less than versionb
1882
 */
1883
int ssl_version_cmp(const SSL_CONNECTION *s, int versiona, int versionb)
1884
0
{
1885
0
    int dtls = SSL_CONNECTION_IS_DTLS(s);
1886
1887
0
    if (versiona == versionb)
1888
0
        return 0;
1889
0
    if (!dtls)
1890
0
        return versiona < versionb ? -1 : 1;
1891
0
    return DTLS_VERSION_LT(versiona, versionb) ? -1 : 1;
1892
0
}
1893
1894
typedef struct {
1895
    int version;
1896
    const SSL_METHOD *(*cmeth)(void);
1897
    const SSL_METHOD *(*smeth)(void);
1898
} version_info;
1899
1900
#if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1901
#error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1902
#endif
1903
1904
/* Must be in order high to low */
1905
static const version_info tls_version_table[] = {
1906
#ifndef OPENSSL_NO_TLS1_3
1907
    { TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method },
1908
#else
1909
    { TLS1_3_VERSION, NULL, NULL },
1910
#endif
1911
#ifndef OPENSSL_NO_TLS1_2
1912
    { TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method },
1913
#else
1914
    { TLS1_2_VERSION, NULL, NULL },
1915
#endif
1916
#ifndef OPENSSL_NO_TLS1_1
1917
    { TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method },
1918
#else
1919
    { TLS1_1_VERSION, NULL, NULL },
1920
#endif
1921
#ifndef OPENSSL_NO_TLS1
1922
    { TLS1_VERSION, tlsv1_client_method, tlsv1_server_method },
1923
#else
1924
    { TLS1_VERSION, NULL, NULL },
1925
#endif
1926
    { 0, NULL, NULL },
1927
};
1928
1929
#if DTLS_MAX_VERSION_INTERNAL != DTLS1_3_VERSION
1930
#error Code needs update for DTLS_method() support beyond DTLS1_3_VERSION.
1931
#endif
1932
1933
/* Must be in order high to low */
1934
static const version_info dtls_version_table[] = {
1935
#ifndef OPENSSL_NO_DTLS1_3
1936
    { DTLS1_3_VERSION, dtlsv1_3_client_method, dtlsv1_3_server_method },
1937
#else
1938
    { DTLS1_3_VERSION, NULL, NULL },
1939
#endif
1940
#ifndef OPENSSL_NO_DTLS1_2
1941
    { DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method },
1942
#else
1943
    { DTLS1_2_VERSION, NULL, NULL },
1944
#endif
1945
#ifndef OPENSSL_NO_DTLS1
1946
    { DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method },
1947
    { DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL },
1948
#else
1949
    { DTLS1_VERSION, NULL, NULL },
1950
    { DTLS1_BAD_VER, NULL, NULL },
1951
#endif
1952
    { 0, NULL, NULL },
1953
};
1954
1955
/*
1956
 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1957
 *
1958
 * @s: The SSL handle for the candidate method
1959
 * @method: the intended method.
1960
 *
1961
 * Returns 0 on success, or an SSL error reason on failure.
1962
 */
1963
static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1964
0
{
1965
0
    int version = method->version;
1966
1967
0
    if ((s->min_proto_version != 0 && ssl_version_cmp(s, version, s->min_proto_version) < 0) || ssl_security(s, SSL_SECOP_VERSION, 0, version, NULL) == 0)
1968
0
        return SSL_R_VERSION_TOO_LOW;
1969
1970
0
    if (s->max_proto_version != 0 && ssl_version_cmp(s, version, s->max_proto_version) > 0)
1971
0
        return SSL_R_VERSION_TOO_HIGH;
1972
1973
0
    if ((s->options & method->mask) != 0)
1974
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
1975
0
    if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1976
0
        return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1977
1978
0
    return 0;
1979
0
}
1980
1981
/*
1982
 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1983
 * certificate type, or has PSK or a certificate callback configured, or has
1984
 * a servername callback configure. Otherwise returns 0.
1985
 */
1986
static int is_tls13_capable(const SSL_CONNECTION *s)
1987
0
{
1988
0
    size_t i;
1989
0
    int curve;
1990
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1991
1992
0
    if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1993
0
        return 0;
1994
1995
    /*
1996
     * A servername callback can change the available certs, so if a servername
1997
     * cb is set then we just assume TLSv1.3 will be ok
1998
     */
1999
0
    if (sctx->ext.servername_cb != NULL
2000
0
        || s->session_ctx->ext.servername_cb != NULL)
2001
0
        return 1;
2002
2003
0
#ifndef OPENSSL_NO_PSK
2004
0
    if (s->psk_server_callback != NULL)
2005
0
        return 1;
2006
0
#endif
2007
2008
0
    if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
2009
0
        return 1;
2010
2011
    /* All provider-based sig algs are required to support at least TLS1.3 */
2012
0
    for (i = 0; i < s->ssl_pkey_num; i++) {
2013
        /* Skip over certs disallowed for TLSv1.3 */
2014
0
        switch (i) {
2015
0
        case SSL_PKEY_DSA_SIGN:
2016
0
        case SSL_PKEY_GOST01:
2017
0
        case SSL_PKEY_GOST12_256:
2018
0
        case SSL_PKEY_GOST12_512:
2019
0
            continue;
2020
0
        default:
2021
0
            break;
2022
0
        }
2023
0
        if (!ssl_has_cert(s, (int)i))
2024
0
            continue;
2025
0
        if (i != SSL_PKEY_ECC)
2026
0
            return 1;
2027
        /*
2028
         * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
2029
         * more restrictive so check that our sig algs are consistent with this
2030
         * EC cert. See section 4.3.3 of RFC9846.
2031
         */
2032
0
        curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
2033
0
        if (tls_check_sigalg_curve(s, curve))
2034
0
            return 1;
2035
0
    }
2036
2037
0
    return 0;
2038
0
}
2039
2040
/*
2041
 * ssl_version_supported - Check that the specified `version` is supported by
2042
 * `SSL *` instance
2043
 *
2044
 * @s: The SSL handle for the candidate method
2045
 * @version: Protocol version to test against
2046
 *
2047
 * Returns 1 when supported, otherwise 0
2048
 */
2049
int ssl_version_supported(const SSL_CONNECTION *s, int version,
2050
    const SSL_METHOD **meth)
2051
0
{
2052
0
    const version_info *vent;
2053
0
    const version_info *table;
2054
2055
0
    switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
2056
0
    default:
2057
        /* Version should match method version for non-ANY method */
2058
0
        return ssl_version_cmp(s, version, s->version) == 0;
2059
0
    case TLS_ANY_VERSION:
2060
0
        table = tls_version_table;
2061
0
        break;
2062
0
    case DTLS_ANY_VERSION:
2063
0
        table = dtls_version_table;
2064
0
        break;
2065
0
    }
2066
2067
0
    for (vent = table;
2068
0
        vent->version != 0 && ssl_version_cmp(s, version, vent->version) <= 0;
2069
0
        ++vent) {
2070
0
        const SSL_METHOD *(*thismeth)(void) = s->server ? vent->smeth
2071
0
                                                        : vent->cmeth;
2072
2073
0
        if (thismeth != NULL
2074
0
            && ssl_version_cmp(s, version, vent->version) == 0
2075
0
            && ssl_method_error(s, thismeth()) == 0
2076
0
            && (!s->server
2077
0
                || (version != TLS1_3_VERSION && version != DTLS1_3_VERSION)
2078
0
                || is_tls13_capable(s))) {
2079
0
            if (meth != NULL)
2080
0
                *meth = thismeth();
2081
0
            return 1;
2082
0
        }
2083
0
    }
2084
0
    return 0;
2085
0
}
2086
2087
/*
2088
 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
2089
 * fallback indication from a client check whether we're using the highest
2090
 * supported protocol version.
2091
 *
2092
 * @s server SSL handle.
2093
 *
2094
 * Returns 1 when using the highest enabled version, 0 otherwise.
2095
 */
2096
int ssl_check_version_downgrade(SSL_CONNECTION *s)
2097
0
{
2098
0
    const version_info *vent;
2099
0
    const version_info *table;
2100
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2101
2102
    /*
2103
     * Check that the current protocol is the highest enabled version
2104
     * (according to ssl->defltmethod, as version negotiation may have changed
2105
     * s->method).
2106
     */
2107
0
    if (s->version == ssl->defltmeth->version)
2108
0
        return 1;
2109
2110
    /*
2111
     * Apparently we're using a version-flexible SSL_METHOD (not at its
2112
     * highest protocol version).
2113
     */
2114
0
    if (ssl->defltmeth->version == TLS_method()->version)
2115
0
        table = tls_version_table;
2116
0
    else if (ssl->defltmeth->version == DTLS_method()->version)
2117
0
        table = dtls_version_table;
2118
0
    else {
2119
        /* Unexpected state; fail closed. */
2120
0
        return 0;
2121
0
    }
2122
2123
0
    for (vent = table; vent->version != 0; ++vent) {
2124
0
        if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
2125
0
            return s->version == vent->version;
2126
0
    }
2127
0
    return 0;
2128
0
}
2129
2130
/*
2131
 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
2132
 * protocols, provided the initial (D)TLS method is version-flexible.  This
2133
 * function sanity-checks the proposed value and makes sure the method is
2134
 * version-flexible, then sets the limit if all is well.
2135
 *
2136
 * @method_version: The version of the current SSL_METHOD.
2137
 * @version: the intended limit.
2138
 * @bound: pointer to limit to be updated.
2139
 *
2140
 * Returns 1 on success, 0 on failure.
2141
 */
2142
int ssl_set_version_bound(int method_version, int version, int *bound)
2143
0
{
2144
0
    int valid_tls;
2145
0
    int valid_dtls;
2146
2147
0
    if (version == 0) {
2148
0
        *bound = version;
2149
0
        return 1;
2150
0
    }
2151
2152
0
    valid_tls = version > SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
2153
0
    valid_dtls =
2154
        /* We support client side pre-standardisation version of DTLS */
2155
0
        (version == DTLS1_BAD_VER)
2156
0
        || (DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL)
2157
0
            && DTLS_VERSION_GE(version, DTLS1_VERSION));
2158
2159
0
    if (!valid_tls && !valid_dtls)
2160
0
        return 0;
2161
2162
    /*-
2163
     * Restrict TLS methods to TLS protocol versions.
2164
     * Restrict DTLS methods to DTLS protocol versions.
2165
     * Note, DTLS version numbers are decreasing, use comparison macros.
2166
     *
2167
     * Note that for both lower-bounds we use explicit versions, not
2168
     * (D)TLS_MIN_VERSION.  This is because we don't want to break user
2169
     * configurations.  If the MIN (supported) version ever rises, the user's
2170
     * "floor" remains valid even if no longer available.  We don't expect the
2171
     * MAX ceiling to ever get lower, so making that variable makes sense.
2172
     *
2173
     * We ignore attempts to set bounds on version-inflexible methods,
2174
     * returning success.
2175
     */
2176
0
    switch (method_version) {
2177
0
    default:
2178
0
        break;
2179
2180
0
    case TLS_ANY_VERSION:
2181
0
        if (valid_tls)
2182
0
            *bound = version;
2183
0
        break;
2184
2185
0
    case DTLS_ANY_VERSION:
2186
0
        if (valid_dtls)
2187
0
            *bound = version;
2188
0
        break;
2189
0
    }
2190
0
    return 1;
2191
0
}
2192
2193
static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
2194
0
{
2195
0
    int version12 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_2_VERSION : TLS1_2_VERSION;
2196
0
    int version13 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_3_VERSION : TLS1_3_VERSION;
2197
2198
0
    if (vers == version12 && ssl_version_supported(s, version13, NULL)) {
2199
0
        *dgrd = DOWNGRADE_TO_1_2;
2200
0
    } else if (ssl_version_cmp(s, vers, version12) < 0
2201
        /*
2202
         * We need to ensure that a server that disables (D)TLSv1.2
2203
         * (creating a hole between (D)TLSv1.3 and (D)TLSv1.1) can still
2204
         * complete handshakes with clients that support (D)TLSv1.2 and
2205
         * below. Therefore we do not enable the sentinel if (D)TLSv1.3 is
2206
         * enabled and (D)TLSv1.2 is not.
2207
         */
2208
0
        && ssl_version_supported(s, version12, NULL)) {
2209
0
        *dgrd = DOWNGRADE_TO_1_1;
2210
0
    } else {
2211
0
        *dgrd = DOWNGRADE_NONE;
2212
0
    }
2213
2214
0
    if (SSL_CONNECTION_IS_DTLS(s))
2215
0
        s->d1->downgrade_after_hvr = *dgrd;
2216
0
}
2217
2218
/*
2219
 * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
2220
 * client HELLO is received to select the final server protocol version and
2221
 * the version specific method.
2222
 *
2223
 * @s: server SSL handle.
2224
 *
2225
 * Returns 0 on success or an SSL error reason number on failure.
2226
 */
2227
int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
2228
    DOWNGRADE *dgrd)
2229
0
{
2230
    /*-
2231
     * With version-flexible methods we have an initial state with:
2232
     *
2233
     *   s->method->version == (D)TLS_ANY_VERSION,
2234
     *   s->version == (D)TLS_MAX_VERSION_INTERNAL.
2235
     *
2236
     * So we detect version-flexible methods via the method version, not the
2237
     * handle version.
2238
     */
2239
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2240
0
    int server_version = ssl->method->version;
2241
0
    int client_version = hello->legacy_version;
2242
0
    const version_info *vent;
2243
0
    const version_info *table;
2244
0
    int disabled = 0;
2245
0
    RAW_EXTENSION *suppversions;
2246
0
    const int version1_3 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_3_VERSION
2247
0
                                                     : TLS1_3_VERSION;
2248
0
    const int version1_2 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_2_VERSION
2249
0
                                                     : TLS1_2_VERSION;
2250
2251
0
    if (client_version <= 0)
2252
0
        return SSL_R_WRONG_SSL_VERSION;
2253
2254
0
    s->client_version = client_version;
2255
2256
0
    switch (server_version) {
2257
0
    default:
2258
0
        if (!SSL_CONNECTION_IS_VERSION13(s)) {
2259
0
            if (ssl_version_cmp(s, client_version, s->version) < 0)
2260
0
                return SSL_R_WRONG_SSL_VERSION;
2261
2262
            /*
2263
             * The downgrade sentinel is selected when parsing the first
2264
             * ClientHello. If this server has sent a HelloVerifyRequest, the
2265
             * sentinel is recovered while parsing the second ClientHello in
2266
             * order to apply it to the ServerHello random value.
2267
             */
2268
0
            if (SSL_CONNECTION_IS_DTLS(s)
2269
0
                && s->d1->hello_verify_request != SSL_HVR_NONE) {
2270
0
                *dgrd = s->d1->downgrade_after_hvr;
2271
0
            } else {
2272
0
                *dgrd = DOWNGRADE_NONE;
2273
0
            }
2274
2275
            /*
2276
             * If this SSL handle is not from a version flexible method we don't
2277
             * (and never did) check min/max FIPS or Suite B constraints.  Hope
2278
             * that's OK.  It is up to the caller to not choose fixed protocol
2279
             * versions they don't want.  If not, then easy to fix, just return
2280
             * ssl_method_error(s, s->method)
2281
             */
2282
0
            return 0;
2283
0
        }
2284
        /*
2285
         * Fall through if we are TLSv1.3 already (this means we must be after
2286
         * a HelloRetryRequest
2287
         */
2288
        /* fall thru */
2289
0
    case TLS_ANY_VERSION:
2290
0
        table = tls_version_table;
2291
0
        break;
2292
0
    case DTLS_ANY_VERSION:
2293
0
        table = dtls_version_table;
2294
0
        break;
2295
0
    }
2296
2297
0
    suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
2298
2299
0
#ifndef OPENSSL_NO_ECH
2300
    /*
2301
     * Check we're dealing with a TLSv1.3 connection when ECH has
2302
     * succeeded, and not with a smuggled earlier version ClientHello
2303
     * (which could be a form of attack).
2304
     * This bit checks there is a supported version present, a little
2305
     * bit further below, we check that that version is TLSv1.3
2306
     */
2307
0
    if (!suppversions->present && s->ext.ech.success == 1)
2308
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
2309
0
#endif
2310
2311
    /* If we did an HRR then supported versions is mandatory */
2312
0
    if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
2313
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
2314
2315
0
    if (suppversions->present) {
2316
0
        int candidate_vers = 0;
2317
0
        const int best_vers_init = SSL_CONNECTION_IS_DTLS(s) ? INT_MAX
2318
0
                                                             : 0;
2319
0
        int best_vers = best_vers_init;
2320
0
        const SSL_METHOD *best_method = NULL;
2321
0
        PACKET versionslist;
2322
2323
0
        suppversions->parsed = 1;
2324
2325
0
        if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
2326
            /* Trailing or invalid data? */
2327
0
            return SSL_R_LENGTH_MISMATCH;
2328
0
        }
2329
2330
        /*
2331
         * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
2332
         * The spec only requires servers to check that it isn't SSLv3:
2333
         * "Any endpoint receiving a Hello message with
2334
         * ClientHello.legacy_version or ServerHello.legacy_version set to
2335
         * 0x0300 MUST abort the handshake with a "protocol_version" alert."
2336
         * We are slightly stricter and require that it isn't SSLv3 or lower.
2337
         * We tolerate TLSv1 and TLSv1.1.
2338
         */
2339
0
        if (client_version <= SSL3_VERSION)
2340
0
            return SSL_R_BAD_LEGACY_VERSION;
2341
2342
0
        while (PACKET_get_net_2(&versionslist, (unsigned int *)&candidate_vers)) {
2343
0
            if (candidate_vers <= 0
2344
0
                || (best_vers != best_vers_init
2345
0
                    && ssl_version_cmp(s, candidate_vers, best_vers) <= 0))
2346
0
                continue;
2347
#ifndef OPENSSL_NO_SCTP
2348
            /*
2349
             * DTLS 1.3 is not supported over SCTP.  If the client offers
2350
             * DTLSv1.3 but the transport is SCTP, thus fall back to
2351
             * DTLSv1.2 (or lower) during server-version selection.
2352
             */
2353
            if (SSL_CONNECTION_IS_DTLS(s)
2354
                && candidate_vers == DTLS1_3_VERSION
2355
                && BIO_dgram_is_sctp(SSL_get_wbio(
2356
                    SSL_CONNECTION_GET_SSL(s))))
2357
                continue;
2358
#endif
2359
0
            if (ssl_version_supported(s, candidate_vers, &best_method))
2360
0
                best_vers = candidate_vers;
2361
0
        }
2362
0
        if (PACKET_remaining(&versionslist) != 0) {
2363
            /* Trailing data? */
2364
0
            return SSL_R_LENGTH_MISMATCH;
2365
0
        }
2366
2367
        /* Did best_vers change from the initial value? */
2368
0
        if (best_vers != best_vers_init) {
2369
0
#ifndef OPENSSL_NO_ECH
2370
            /* ECH needs TLSV1.3 also */
2371
0
            if (s->ext.ech.success == 1 && best_vers != TLS1_3_VERSION)
2372
0
                return SSL_R_UNSUPPORTED_PROTOCOL;
2373
0
#endif
2374
0
            if (s->hello_retry_request != SSL_HRR_NONE) {
2375
                /*
2376
                 * This is after a HelloRetryRequest so we better check that we
2377
                 * negotiated (D)TLSv1.3
2378
                 */
2379
0
                if (best_vers != version1_3)
2380
0
                    return SSL_R_UNSUPPORTED_PROTOCOL;
2381
0
                return 0;
2382
0
            }
2383
0
            check_for_downgrade(s, best_vers, dgrd);
2384
0
            s->version = best_vers;
2385
0
            ssl->method = best_method;
2386
0
            if (!ssl_set_record_protocol_version(s, best_vers))
2387
0
                return ERR_R_INTERNAL_ERROR;
2388
2389
0
            return 0;
2390
0
        }
2391
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
2392
0
    }
2393
2394
    /*
2395
     * If the supported versions extension isn't present, then the highest
2396
     * version we can negotiate is (D)TLSv1.2
2397
     */
2398
0
    if (ssl_version_cmp(s, client_version, version1_3) >= 0)
2399
0
        client_version = version1_2;
2400
2401
    /*
2402
     * No supported versions extension, so we just use the version supplied in
2403
     * the ClientHello.
2404
     */
2405
0
    for (vent = table; vent->version != 0; ++vent) {
2406
0
        const SSL_METHOD *method;
2407
2408
0
        if (vent->smeth == NULL || ssl_version_cmp(s, client_version, vent->version) < 0)
2409
0
            continue;
2410
0
        method = vent->smeth();
2411
0
        if (ssl_method_error(s, method) == 0) {
2412
0
            check_for_downgrade(s, vent->version, dgrd);
2413
0
            s->version = vent->version;
2414
0
            ssl->method = method;
2415
0
            if (!ssl_set_record_protocol_version(s, s->version))
2416
0
                return ERR_R_INTERNAL_ERROR;
2417
2418
0
            return 0;
2419
0
        }
2420
0
        disabled = 1;
2421
0
    }
2422
0
    return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
2423
0
}
2424
2425
/*
2426
 * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
2427
 * server HELLO is received to select the final client protocol version and
2428
 * the version specific method.
2429
 *
2430
 * @s: client SSL handle.
2431
 * @version: The proposed version from the server's HELLO.
2432
 * @extensions: The extensions received
2433
 *
2434
 * Returns 1 on success or 0 on error.
2435
 */
2436
int ssl_choose_client_version(SSL_CONNECTION *s, int version,
2437
    RAW_EXTENSION *extensions)
2438
0
{
2439
0
    const version_info *vent;
2440
0
    const version_info *table;
2441
0
    int ret, ver_min, ver_max, real_max, origv;
2442
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2443
0
    const int version1_3 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_3_VERSION
2444
0
                                                     : TLS1_3_VERSION;
2445
2446
0
    origv = s->version;
2447
0
    s->version = version;
2448
2449
    /* This will overwrite s->version if the extension is present */
2450
0
    if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
2451
0
            SSL_EXT_TLS1_2_SERVER_HELLO
2452
0
                | SSL_EXT_TLS1_3_SERVER_HELLO,
2453
0
            extensions,
2454
0
            NULL, 0)) {
2455
0
        s->version = origv;
2456
0
        return 0;
2457
0
    }
2458
2459
0
    if (s->hello_retry_request != SSL_HRR_NONE && s->version != version1_3) {
2460
0
        s->version = origv;
2461
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2462
0
        return 0;
2463
0
    }
2464
2465
#ifndef OPENSSL_NO_SCTP
2466
    /*
2467
     * DTLS 1.3 over SCTP is not supported.  If the server selected
2468
     * DTLSv1.3 but the transport is SCTP, treat it as a protocol
2469
     * version mismatch so the handshake is aborted cleanly.
2470
     */
2471
    if (SSL_CONNECTION_IS_DTLS(s)
2472
        && s->version == DTLS1_3_VERSION
2473
        && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
2474
        s->version = origv;
2475
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2476
        return 0;
2477
    }
2478
#endif
2479
2480
0
    switch (ssl->method->version) {
2481
0
    default:
2482
0
        if (s->version != ssl->method->version) {
2483
0
            s->version = origv;
2484
0
            SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2485
0
            return 0;
2486
0
        }
2487
        /*
2488
         * If this SSL handle is not from a version flexible method we don't
2489
         * (and never did) check min/max, FIPS or Suite B constraints.  Hope
2490
         * that's OK.  It is up to the caller to not choose fixed protocol
2491
         * versions they don't want.  If not, then easy to fix, just return
2492
         * ssl_method_error(s, s->method)
2493
         */
2494
0
        if (!ssl_set_record_protocol_version(s, s->version)) {
2495
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2496
0
            return 0;
2497
0
        }
2498
0
        return 1;
2499
0
    case TLS_ANY_VERSION:
2500
0
        table = tls_version_table;
2501
0
        break;
2502
0
    case DTLS_ANY_VERSION:
2503
0
        table = dtls_version_table;
2504
0
        break;
2505
0
    }
2506
2507
0
    ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2508
0
    if (ret != 0) {
2509
0
        s->version = origv;
2510
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2511
0
        return 0;
2512
0
    }
2513
0
    if (ssl_version_cmp(s, s->version, ver_min) < 0
2514
0
        || ssl_version_cmp(s, s->version, ver_max) > 0) {
2515
0
        s->version = origv;
2516
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2517
0
        return 0;
2518
0
    }
2519
2520
0
    if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2521
0
        real_max = ver_max;
2522
2523
    /* Check for downgrades */
2524
0
    if (ssl_version_cmp(s, real_max, s->version) > 0) {
2525
        /* Signal applies to all versions */
2526
0
        if (memcmp(tls11downgrade,
2527
0
                s->s3.server_random + SSL3_RANDOM_SIZE
2528
0
                    - sizeof(tls11downgrade),
2529
0
                sizeof(tls11downgrade))
2530
0
            == 0) {
2531
0
            s->version = origv;
2532
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2533
0
                SSL_R_INAPPROPRIATE_FALLBACK);
2534
0
            return 0;
2535
0
        }
2536
        /* Only when accepting (D)TLS1.3 */
2537
0
        if (ssl_version_cmp(s, s->version, version1_3)
2538
0
            && memcmp(tls12downgrade,
2539
0
                   s->s3.server_random + SSL3_RANDOM_SIZE
2540
0
                       - sizeof(tls12downgrade),
2541
0
                   sizeof(tls12downgrade))
2542
0
                == 0) {
2543
0
            s->version = origv;
2544
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2545
0
                SSL_R_INAPPROPRIATE_FALLBACK);
2546
0
            return 0;
2547
0
        }
2548
0
    }
2549
2550
0
    for (vent = table; vent->version != 0; ++vent) {
2551
0
        if (vent->cmeth == NULL || s->version != vent->version)
2552
0
            continue;
2553
2554
0
        ssl->method = vent->cmeth();
2555
0
        if (!ssl_set_record_protocol_version(s, s->version)) {
2556
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2557
0
            return 0;
2558
0
        }
2559
0
        return 1;
2560
0
    }
2561
2562
0
    s->version = origv;
2563
0
    SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2564
0
    return 0;
2565
0
}
2566
2567
/*
2568
 * ssl_get_min_max_version - get minimum and maximum protocol version
2569
 * @s: The SSL connection
2570
 * @min_version: The minimum supported version
2571
 * @max_version: The maximum supported version
2572
 * @real_max:    The highest version below the lowest compile time version hole
2573
 *               where that hole lies above at least one run-time enabled
2574
 *               protocol.
2575
 *
2576
 * Work out what version we should be using for the initial ClientHello if the
2577
 * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
2578
 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2579
 * constraints and any floor imposed by the security level here,
2580
 * so we don't advertise the wrong protocol version to only reject the outcome later.
2581
 *
2582
 * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
2583
 * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
2584
 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2585
 *
2586
 * Returns 0 on success or an SSL error reason number on failure.  On failure
2587
 * min_version and max_version will also be set to 0.
2588
 */
2589
int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2590
    int *max_version, int *real_max)
2591
0
{
2592
0
    int version, tmp_real_max;
2593
0
    int hole;
2594
0
    const SSL_METHOD *method;
2595
0
    const version_info *table;
2596
0
    const version_info *vent;
2597
0
    const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2598
2599
0
    switch (ssl->method->version) {
2600
0
    default:
2601
        /*
2602
         * If this SSL handle is not from a version flexible method we don't
2603
         * (and never did) check min/max FIPS or Suite B constraints.  Hope
2604
         * that's OK.  It is up to the caller to not choose fixed protocol
2605
         * versions they don't want.  If not, then easy to fix, just return
2606
         * ssl_method_error(s, s->method)
2607
         */
2608
0
        *min_version = *max_version = s->version;
2609
        /*
2610
         * Providing a real_max only makes sense where we're using a version
2611
         * flexible method.
2612
         */
2613
0
        if (!ossl_assert(real_max == NULL))
2614
0
            return ERR_R_INTERNAL_ERROR;
2615
0
        return 0;
2616
0
    case TLS_ANY_VERSION:
2617
0
        table = tls_version_table;
2618
0
        break;
2619
0
    case DTLS_ANY_VERSION:
2620
0
        table = dtls_version_table;
2621
0
        break;
2622
0
    }
2623
2624
    /*
2625
     * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2626
     * below X enabled. This is required in order to maintain the "version
2627
     * capability" vector contiguous. Any versions with a NULL client method
2628
     * (protocol version client is disabled at compile-time) is also a "hole".
2629
     *
2630
     * Our initial state is hole == 1, version == 0.  That is, versions above
2631
     * the first version in the method table are disabled (a "hole" above
2632
     * the valid protocol entries) and we don't have a selected version yet.
2633
     *
2634
     * Whenever "hole == 1", and we hit an enabled method, its version becomes
2635
     * the selected version.  We're no longer in a hole, so "hole" becomes 0.
2636
     *
2637
     * If "hole == 0" and we hit an enabled method, we support a contiguous
2638
     * range of at least two methods.  If we hit a disabled method,
2639
     * then hole becomes true again, but nothing else changes yet,
2640
     * because all the remaining methods may be disabled too.
2641
     * If we again hit an enabled method after the new hole, it becomes
2642
     * selected, as we start from scratch.
2643
     */
2644
0
    *min_version = version = 0;
2645
0
    hole = 1;
2646
0
    if (real_max != NULL)
2647
0
        *real_max = 0;
2648
0
    tmp_real_max = 0;
2649
0
    for (vent = table; vent->version != 0; ++vent) {
2650
        /*
2651
         * A table entry with a NULL client method is still a hole in the
2652
         * "version capability" vector.
2653
         */
2654
0
        if (vent->cmeth == NULL) {
2655
0
            hole = 1;
2656
0
            tmp_real_max = 0;
2657
0
            continue;
2658
0
        }
2659
/*
2660
 * DTLS 1.3 over SCTP is not supported.  RFC 6083 and its successors only
2661
 * define key-material export for DTLS 1.2 and below.
2662
 */
2663
#ifndef OPENSSL_NO_SCTP
2664
        if (SSL_CONNECTION_IS_DTLS(s) && DTLS_VERSION_GT(vent->version, DTLS1_2_VERSION)) {
2665
            BIO *wbio = SSL_get_wbio(SSL_CONNECTION_GET_SSL(s));
2666
2667
            if (wbio != NULL && BIO_dgram_is_sctp(wbio))
2668
                continue;
2669
        }
2670
#endif
2671
0
        method = vent->cmeth();
2672
2673
0
        if (hole == 1 && tmp_real_max == 0)
2674
0
            tmp_real_max = vent->version;
2675
2676
0
        if (ssl_method_error(s, method) != 0) {
2677
0
            hole = 1;
2678
0
        } else if (!hole) {
2679
0
            *min_version = method->version;
2680
0
        } else {
2681
0
            if (real_max != NULL && tmp_real_max != 0)
2682
0
                *real_max = tmp_real_max;
2683
0
            version = method->version;
2684
0
            *min_version = version;
2685
0
            hole = 0;
2686
0
        }
2687
0
    }
2688
2689
0
    *max_version = version;
2690
2691
    /* Fail if everything is disabled */
2692
0
    if (version == 0)
2693
0
        return SSL_R_NO_PROTOCOLS_AVAILABLE;
2694
2695
0
    return 0;
2696
0
}
2697
2698
/*
2699
 * ssl_set_client_hello_version - Work out what version we should be using for
2700
 * the initial ClientHello.legacy_version field.
2701
 *
2702
 * @s: client SSL handle.
2703
 *
2704
 * Returns 0 on success or an SSL error reason number on failure.
2705
 */
2706
int ssl_set_client_hello_version(SSL_CONNECTION *s)
2707
0
{
2708
0
    int ver_min, ver_max, ret;
2709
0
    const int version1_2 = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_2_VERSION : TLS1_2_VERSION;
2710
2711
    /*
2712
     * In a renegotiation we always send the same client_version that we sent
2713
     * last time, regardless of which version we eventually negotiated.
2714
     */
2715
0
    if (!SSL_IS_FIRST_HANDSHAKE(s))
2716
0
        return 0;
2717
2718
0
    ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2719
2720
0
    if (ret != 0)
2721
0
        return ret;
2722
2723
0
    s->version = ver_max;
2724
2725
0
    if (SSL_CONNECTION_IS_DTLS(s) && ver_max == DTLS1_BAD_VER) {
2726
        /*
2727
         * Even though this is technically before version negotiation,
2728
         * because we have asked for DTLS1_BAD_VER we will never negotiate
2729
         * anything else, and this has impacts on the record layer for when
2730
         * we read the ServerHello. So we need to tell the record layer
2731
         * about this immediately.
2732
         */
2733
0
        if (!ssl_set_record_protocol_version(s, ver_max))
2734
0
            return 0;
2735
0
    } else if (ssl_version_cmp(s, ver_max, version1_2) > 0) {
2736
        /* (D)TLS1.3 always uses (D)TLS1.2 in the legacy_version field */
2737
0
        ver_max = version1_2;
2738
0
    }
2739
2740
0
    s->client_version = ver_max;
2741
0
    return 0;
2742
0
}
2743
2744
/*
2745
 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2746
 * and |checkallow| is 1 then additionally check if the group is allowed to be
2747
 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2748
 * 1) or 0 otherwise. If provided a pointer it will also return the position
2749
 * where the group was found.
2750
 */
2751
int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2752
    size_t num_groups, int checkallow, size_t *pos)
2753
0
{
2754
0
    size_t i;
2755
2756
0
    if (groups == NULL || num_groups == 0)
2757
0
        return 0;
2758
2759
0
    for (i = 0; i < num_groups; i++) {
2760
0
        uint16_t group = groups[i];
2761
2762
0
        if (group_id == group
2763
0
            && (!checkallow
2764
0
                || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2765
0
            if (pos != NULL)
2766
0
                *pos = i;
2767
0
            return 1;
2768
0
        }
2769
0
    }
2770
2771
0
    return 0;
2772
0
}
2773
2774
/* Replace ClientHello1 in the transcript hash with a synthetic message */
2775
int create_synthetic_message_hash(SSL_CONNECTION *s,
2776
    const unsigned char *hashval,
2777
    size_t hashlen, const unsigned char *hrr,
2778
    size_t hrrlen)
2779
0
{
2780
0
    unsigned char *hashvaltmp;
2781
0
    unsigned char synmsg[SSL3_HM_HEADER_LENGTH + EVP_MAX_MD_SIZE];
2782
0
    size_t currmsghdr_len = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_HM_HEADER_LENGTH
2783
0
                                                      : SSL3_HM_HEADER_LENGTH;
2784
2785
0
    memset(synmsg, 0, SSL3_HM_HEADER_LENGTH);
2786
0
    hashvaltmp = synmsg + SSL3_HM_HEADER_LENGTH;
2787
2788
0
    if (hashval == NULL) {
2789
        /* Get the hash of the initial ClientHello */
2790
0
        if (!ssl3_digest_cached_records(s, 0)
2791
0
            || !ssl_handshake_hash(s, hashvaltmp, EVP_MAX_MD_SIZE,
2792
0
                &hashlen)) {
2793
            /* SSLfatal() already called */
2794
0
            return 0;
2795
0
        }
2796
0
    } else {
2797
0
        if (!ossl_assert(hashlen <= EVP_MAX_MD_SIZE))
2798
0
            return 0;
2799
2800
0
        memcpy(hashvaltmp, hashval, hashlen);
2801
0
    }
2802
2803
    /* Reinitialise the transcript hash */
2804
0
    if (!ssl3_init_finished_mac(s)) {
2805
        /* SSLfatal() already called */
2806
0
        return 0;
2807
0
    }
2808
2809
    /* Inject the synthetic message_hash message */
2810
0
    synmsg[0] = SSL3_MT_MESSAGE_HASH;
2811
0
    synmsg[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2812
0
    if (!ssl3_finish_mac(s, synmsg, SSL3_HM_HEADER_LENGTH + hashlen)) {
2813
        /* SSLfatal() already called */
2814
0
        return 0;
2815
0
    }
2816
2817
    /*
2818
     * Now re-inject the HRR and current message if appropriate (we just deleted
2819
     * it when we reinitialised the transcript hash above). Only necessary after
2820
     * receiving a ClientHello2 with a cookie.
2821
     */
2822
0
    if (hrr != NULL
2823
0
        && (!ssl3_finish_mac(s, hrr, hrrlen)
2824
0
            || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2825
0
                s->s3.tmp.message_size + currmsghdr_len))) {
2826
        /* SSLfatal() already called */
2827
0
        return 0;
2828
0
    }
2829
2830
0
    return 1;
2831
0
}
2832
2833
static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2834
0
{
2835
0
    return X509_NAME_cmp(*a, *b);
2836
0
}
2837
2838
int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2839
0
{
2840
0
    STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2841
0
    X509_NAME *xn = NULL;
2842
0
    PACKET cadns;
2843
2844
0
    if (ca_sk == NULL) {
2845
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2846
0
        goto err;
2847
0
    }
2848
    /* get the CA RDNs */
2849
0
    if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2850
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2851
0
        goto err;
2852
0
    }
2853
2854
0
    while (PACKET_remaining(&cadns)) {
2855
0
        const unsigned char *namestart, *namebytes;
2856
0
        unsigned int name_len;
2857
2858
0
        if (!PACKET_get_net_2(&cadns, &name_len)
2859
0
            || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2860
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2861
0
            goto err;
2862
0
        }
2863
2864
0
        namestart = namebytes;
2865
0
        if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2866
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2867
0
            goto err;
2868
0
        }
2869
0
        if (namebytes != (namestart + name_len)) {
2870
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2871
0
            goto err;
2872
0
        }
2873
2874
0
        if (!sk_X509_NAME_push(ca_sk, xn)) {
2875
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2876
0
            goto err;
2877
0
        }
2878
0
        xn = NULL;
2879
0
    }
2880
2881
0
    sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2882
0
    s->s3.tmp.peer_ca_names = ca_sk;
2883
2884
0
    return 1;
2885
2886
0
err:
2887
0
    sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2888
0
    X509_NAME_free(xn);
2889
0
    return 0;
2890
0
}
2891
2892
const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2893
0
{
2894
0
    const STACK_OF(X509_NAME) *ca_sk = NULL;
2895
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2896
2897
0
    if (s->server) {
2898
0
        ca_sk = SSL_get_client_CA_list(ssl);
2899
0
        if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2900
0
            ca_sk = NULL;
2901
0
    }
2902
2903
0
    if (ca_sk == NULL)
2904
0
        ca_sk = SSL_get0_CA_list(ssl);
2905
2906
0
    return ca_sk;
2907
0
}
2908
2909
int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2910
    WPACKET *pkt)
2911
0
{
2912
    /* Start sub-packet for client CA list */
2913
0
    if (!WPACKET_start_sub_packet_u16(pkt)) {
2914
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2915
0
        return 0;
2916
0
    }
2917
2918
0
    if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2919
0
        int i;
2920
2921
0
        for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2922
0
            unsigned char *namebytes;
2923
0
            X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2924
0
            int namelen;
2925
2926
0
            if (name == NULL
2927
0
                || (namelen = i2d_X509_NAME(name, NULL)) < 0
2928
0
                || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2929
0
                    &namebytes)
2930
0
                || i2d_X509_NAME(name, &namebytes) != namelen) {
2931
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2932
0
                return 0;
2933
0
            }
2934
0
        }
2935
0
    }
2936
2937
0
    if (!WPACKET_close(pkt)) {
2938
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2939
0
        return 0;
2940
0
    }
2941
2942
0
    return 1;
2943
0
}
2944
2945
/* Create a buffer containing data to be signed for server key exchange */
2946
size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2947
    const void *param, size_t paramlen)
2948
0
{
2949
0
    size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2950
0
    unsigned char *tbs = OPENSSL_malloc(tbslen);
2951
2952
0
    if (tbs == NULL) {
2953
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2954
0
        return 0;
2955
0
    }
2956
0
    memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2957
0
    memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2958
2959
0
    memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2960
2961
0
    *ptbs = tbs;
2962
0
    return tbslen;
2963
0
}
2964
2965
/*
2966
 * Saves the current handshake digest for Post-Handshake Auth,
2967
 * Done after ClientFinished is processed, done exactly once
2968
 */
2969
int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2970
0
{
2971
0
    if (s->pha_dgst == NULL) {
2972
0
        if (!ssl3_digest_cached_records(s, 1))
2973
            /* SSLfatal() already called */
2974
0
            return 0;
2975
2976
0
        s->pha_dgst = EVP_MD_CTX_new();
2977
0
        if (s->pha_dgst == NULL) {
2978
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2979
0
            return 0;
2980
0
        }
2981
0
        if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2982
0
                s->s3.handshake_dgst)) {
2983
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2984
0
            EVP_MD_CTX_free(s->pha_dgst);
2985
0
            s->pha_dgst = NULL;
2986
0
            return 0;
2987
0
        }
2988
0
    }
2989
0
    return 1;
2990
0
}
2991
2992
/*
2993
 * Restores the Post-Handshake Auth handshake digest
2994
 * Done just before sending/processing the Cert Request
2995
 */
2996
int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2997
0
{
2998
0
    if (s->pha_dgst == NULL) {
2999
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3000
0
        return 0;
3001
0
    }
3002
0
    if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
3003
0
            s->pha_dgst)) {
3004
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3005
0
        return 0;
3006
0
    }
3007
0
    return 1;
3008
0
}
3009
3010
#ifndef OPENSSL_NO_COMP_ALG
3011
MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
3012
    PACKET *pkt,
3013
    PACKET *tmppkt,
3014
    BUF_MEM *buf)
3015
{
3016
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3017
    int comp_alg;
3018
    COMP_METHOD *method = NULL;
3019
    COMP_CTX *comp = NULL;
3020
    size_t expected_length;
3021
    size_t comp_length;
3022
    int i;
3023
    int found = 0;
3024
3025
    if (buf == NULL) {
3026
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3027
        goto err;
3028
    }
3029
    if (!PACKET_get_net_2(pkt, (unsigned int *)&comp_alg)) {
3030
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3031
        goto err;
3032
    }
3033
    /* If we have a prefs list, make sure the algorithm is in it */
3034
    if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
3035
        for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
3036
            if (sc->cert_comp_prefs[i] == comp_alg) {
3037
                found = 1;
3038
                break;
3039
            }
3040
        }
3041
        if (!found) {
3042
            SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_COMPRESSION_ALGORITHM);
3043
            goto err;
3044
        }
3045
    }
3046
    if (!ossl_comp_has_alg(comp_alg)) {
3047
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
3048
        goto err;
3049
    }
3050
    switch (comp_alg) {
3051
    case TLSEXT_comp_cert_zlib:
3052
        method = COMP_zlib_oneshot();
3053
        break;
3054
    case TLSEXT_comp_cert_brotli:
3055
        method = COMP_brotli_oneshot();
3056
        break;
3057
    case TLSEXT_comp_cert_zstd:
3058
        method = COMP_zstd_oneshot();
3059
        break;
3060
    default:
3061
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
3062
        goto err;
3063
    }
3064
3065
    if ((comp = COMP_CTX_new(method)) == NULL
3066
        || !PACKET_get_net_3_len(pkt, &expected_length)
3067
        || !PACKET_get_net_3_len(pkt, &comp_length)) {
3068
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
3069
        goto err;
3070
    }
3071
3072
    /* Prevent excessive pre-decompression allocation */
3073
    if (expected_length > sc->max_cert_list) {
3074
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
3075
        goto err;
3076
    }
3077
3078
    if (PACKET_remaining(pkt) != comp_length || comp_length == 0) {
3079
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_DECOMPRESSION);
3080
        goto err;
3081
    }
3082
3083
    if (!BUF_MEM_grow(buf, expected_length)
3084
        || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
3085
        || COMP_expand_block(comp, (unsigned char *)buf->data, (int)expected_length,
3086
               (unsigned char *)PACKET_data(pkt),
3087
               (int)comp_length)
3088
            != (int)expected_length) {
3089
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
3090
        goto err;
3091
    }
3092
    ret = MSG_PROCESS_CONTINUE_PROCESSING;
3093
err:
3094
    COMP_CTX_free(comp);
3095
    return ret;
3096
}
3097
#endif