Coverage Report

Created: 2026-07-16 07:11

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 = (int)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
        int negotiated_minversion;
163
0
        int md5sha1_needed_maxversion = SSL_CONNECTION_IS_DTLS(s)
164
0
            ? 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, md5sha1_needed_maxversion) <= 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
        negotiated_minversion = SSL_CONNECTION_IS_DTLS(s) ? DTLS1_2_VERSION : TLS1_2_VERSION;
182
0
        if (ssl_version_cmp(s, ver_min, negotiated_minversion) < 0)
183
0
            ok = SSL_set_min_proto_version(ssl, negotiated_minversion);
184
0
        if (!ok) {
185
            /* Shouldn't happen */
186
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
187
0
            return 0;
188
0
        }
189
0
    }
190
191
0
    ok = 0;
192
0
    if (s->server) {
193
0
        STACK_OF(SSL_CIPHER) *ciphers = SSL_get_ciphers(ssl);
194
0
        int i;
195
196
        /*
197
         * Sanity check that the maximum version we accept has ciphers
198
         * enabled. For clients we do this check during construction of the
199
         * ClientHello.
200
         */
201
0
        for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
202
0
            const SSL_CIPHER *c = sk_SSL_CIPHER_value(ciphers, i);
203
0
            int cipher_minprotover = SSL_CONNECTION_IS_DTLS(s)
204
0
                ? c->min_dtls
205
0
                : c->min_tls;
206
0
            int cipher_maxprotover = SSL_CONNECTION_IS_DTLS(s)
207
0
                ? c->max_dtls
208
0
                : c->max_tls;
209
210
0
            if (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_TLS13(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 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 TLSv1.3 the CertificateRequest
585
     * comes *before* the Certificate message. In 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_TLS13(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_TLS13(s)
621
0
        && !s->server
622
0
        && !SSL_IS_QUIC_HANDSHAKE(s)
623
0
        && (s->early_data_state != SSL_EARLY_DATA_NONE
624
0
            || (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
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
     * TLSv1.3: there's a different key schedule for that.
659
     */
660
0
    if (!SSL_CONNECTION_IS_TLS13(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
     */
732
0
    if (updatetype == SSL_KEY_UPDATE_REQUESTED)
733
0
        s->key_update = SSL_KEY_UPDATE_NOT_REQUESTED;
734
735
0
    if (!tls13_update_key(s, 0)) {
736
        /* SSLfatal() already called */
737
0
        return MSG_PROCESS_ERROR;
738
0
    }
739
740
0
    return MSG_PROCESS_FINISHED_READING;
741
0
}
742
743
/*
744
 * ssl3_take_mac calculates the Finished MAC for the handshakes messages seen
745
 * to far.
746
 */
747
int ssl3_take_mac(SSL_CONNECTION *s)
748
0
{
749
0
    const char *sender;
750
0
    size_t slen;
751
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
752
753
0
    if (!s->server) {
754
0
        sender = ssl->method->ssl3_enc->server_finished_label;
755
0
        slen = ssl->method->ssl3_enc->server_finished_label_len;
756
0
    } else {
757
0
        sender = ssl->method->ssl3_enc->client_finished_label;
758
0
        slen = ssl->method->ssl3_enc->client_finished_label_len;
759
0
    }
760
761
0
    s->s3.tmp.peer_finish_md_len = ssl->method->ssl3_enc->final_finish_mac(s, sender, slen,
762
0
        s->s3.tmp.peer_finish_md);
763
764
0
    if (s->s3.tmp.peer_finish_md_len == 0) {
765
        /* SSLfatal() already called */
766
0
        return 0;
767
0
    }
768
769
0
    return 1;
770
0
}
771
772
MSG_PROCESS_RETURN tls_process_change_cipher_spec(SSL_CONNECTION *s,
773
    PACKET *pkt)
774
0
{
775
0
    size_t remain;
776
777
0
    remain = PACKET_remaining(pkt);
778
    /*
779
     * 'Change Cipher Spec' is just a single byte, which should already have
780
     * been consumed by ssl_get_message() so there should be no bytes left,
781
     * unless we're using DTLS1_BAD_VER, which has an extra 2 bytes
782
     */
783
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
784
0
        if ((s->version == DTLS1_BAD_VER
785
0
                && remain != DTLS1_CCS_HEADER_LENGTH + 1)
786
0
            || (s->version != DTLS1_BAD_VER
787
0
                && remain != DTLS1_CCS_HEADER_LENGTH - 1)) {
788
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
789
0
            return MSG_PROCESS_ERROR;
790
0
        }
791
0
    } else {
792
0
        if (remain != 0) {
793
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_CHANGE_CIPHER_SPEC);
794
0
            return MSG_PROCESS_ERROR;
795
0
        }
796
0
    }
797
798
    /* Check we have a cipher to change to */
799
0
    if (s->s3.tmp.new_cipher == NULL) {
800
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
801
0
        return MSG_PROCESS_ERROR;
802
0
    }
803
804
0
    s->s3.change_cipher_spec = 1;
805
0
    if (!ssl3_do_change_cipher_spec(s)) {
806
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
807
0
        return MSG_PROCESS_ERROR;
808
0
    }
809
810
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
811
0
        if (s->version == DTLS1_BAD_VER)
812
0
            s->d1->handshake_read_seq++;
813
814
#ifndef OPENSSL_NO_SCTP
815
        /*
816
         * Remember that a CCS has been received, so that an old key of
817
         * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
818
         * SCTP is used
819
         */
820
        BIO_ctrl(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)),
821
            BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
822
#endif
823
0
    }
824
825
0
    return MSG_PROCESS_CONTINUE_READING;
826
0
}
827
828
MSG_PROCESS_RETURN tls_process_finished(SSL_CONNECTION *s, PACKET *pkt)
829
0
{
830
0
    size_t md_len;
831
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
832
0
    int was_first = SSL_IS_FIRST_HANDSHAKE(s);
833
0
    int ok;
834
835
    /* This is a real handshake so make sure we clean it up at the end */
836
0
    if (s->server) {
837
        /*
838
         * To get this far we must have read encrypted data from the client. We
839
         * no longer tolerate unencrypted alerts. This is ignored if less than
840
         * TLSv1.3
841
         */
842
0
        if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
843
0
            s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
844
0
        if (s->post_handshake_auth != SSL_PHA_REQUESTED)
845
0
            s->statem.cleanuphand = 1;
846
0
        if (SSL_CONNECTION_IS_TLS13(s)
847
0
            && !tls13_save_handshake_digest_for_pha(s)) {
848
            /* SSLfatal() already called */
849
0
            return MSG_PROCESS_ERROR;
850
0
        }
851
0
    }
852
853
    /*
854
     * In TLSv1.3 a Finished message signals a key change so the end of the
855
     * message must be on a record boundary.
856
     */
857
0
    if (SSL_CONNECTION_IS_TLS13(s)
858
0
        && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
859
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
860
0
        return MSG_PROCESS_ERROR;
861
0
    }
862
863
    /* If this occurs, we have missed a message */
864
0
    if (!SSL_CONNECTION_IS_TLS13(s) && !s->s3.change_cipher_spec) {
865
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_GOT_A_FIN_BEFORE_A_CCS);
866
0
        return MSG_PROCESS_ERROR;
867
0
    }
868
0
    s->s3.change_cipher_spec = 0;
869
870
0
    md_len = s->s3.tmp.peer_finish_md_len;
871
872
0
    if (md_len != PACKET_remaining(pkt)) {
873
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DIGEST_LENGTH);
874
0
        return MSG_PROCESS_ERROR;
875
0
    }
876
877
0
    ok = CRYPTO_memcmp(PACKET_data(pkt), s->s3.tmp.peer_finish_md,
878
0
        md_len);
879
0
#ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
880
0
    if (ok != 0) {
881
0
        if ((PACKET_data(pkt)[0] ^ s->s3.tmp.peer_finish_md[0]) != 0xFF) {
882
0
            ok = 0;
883
0
        }
884
0
    }
885
0
#endif
886
0
    if (ok != 0) {
887
0
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DIGEST_CHECK_FAILED);
888
0
        return MSG_PROCESS_ERROR;
889
0
    }
890
891
    /*
892
     * Copy the finished so we can use it for renegotiation checks
893
     */
894
0
    if (!ossl_assert(md_len <= EVP_MAX_MD_SIZE)) {
895
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
896
0
        return MSG_PROCESS_ERROR;
897
0
    }
898
0
    if (s->server) {
899
0
        memcpy(s->s3.previous_client_finished, s->s3.tmp.peer_finish_md,
900
0
            md_len);
901
0
        s->s3.previous_client_finished_len = md_len;
902
0
    } else {
903
0
        memcpy(s->s3.previous_server_finished, s->s3.tmp.peer_finish_md,
904
0
            md_len);
905
0
        s->s3.previous_server_finished_len = md_len;
906
0
    }
907
908
    /*
909
     * In TLS1.3 we also have to change cipher state and do any final processing
910
     * of the initial server flight (if we are a client)
911
     */
912
0
    if (SSL_CONNECTION_IS_TLS13(s)) {
913
0
        if (s->server) {
914
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)) {
915
                /* SSLfatal() already called */
916
0
                return MSG_PROCESS_ERROR;
917
0
            }
918
0
        } else {
919
            /* TLS 1.3 gets the secret size from the handshake md */
920
0
            size_t dummy;
921
0
            if (!ssl->method->ssl3_enc->generate_master_secret(s,
922
0
                    s->master_secret, s->handshake_secret, 0,
923
0
                    &dummy)) {
924
                /* SSLfatal() already called */
925
0
                return MSG_PROCESS_ERROR;
926
0
            }
927
0
            if (!tls13_store_server_finished_hash(s)) {
928
                /* SSLfatal() already called */
929
0
                return MSG_PROCESS_ERROR;
930
0
            }
931
932
            /*
933
             * For non-QUIC we set up the client's app data read keys now, so
934
             * that we can go straight into reading 0.5RTT data from the server.
935
             * For QUIC we don't do that, and instead defer setting up the keys
936
             * until after we have set up the write keys in order to ensure that
937
             * write keys are always set up before read keys (so that if we read
938
             * a message we have the correct keys in place to ack it)
939
             */
940
0
            if (!SSL_IS_QUIC_HANDSHAKE(s)
941
0
                && !ssl->method->ssl3_enc->change_cipher_state(s,
942
0
                    SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
943
                /* SSLfatal() already called */
944
0
                return MSG_PROCESS_ERROR;
945
0
            }
946
0
            if (!tls_process_initial_server_flight(s)) {
947
                /* SSLfatal() already called */
948
0
                return MSG_PROCESS_ERROR;
949
0
            }
950
0
        }
951
0
    }
952
953
0
    if (was_first
954
0
        && !SSL_IS_FIRST_HANDSHAKE(s)
955
0
        && s->rlayer.rrlmethod->set_first_handshake != NULL)
956
0
        s->rlayer.rrlmethod->set_first_handshake(s->rlayer.rrl, 0);
957
958
0
    return MSG_PROCESS_FINISHED_READING;
959
0
}
960
961
CON_FUNC_RETURN tls_construct_change_cipher_spec(SSL_CONNECTION *s, WPACKET *pkt)
962
0
{
963
0
    if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS)) {
964
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
965
0
        return CON_FUNC_ERROR;
966
0
    }
967
968
0
    return CON_FUNC_SUCCESS;
969
0
}
970
971
/* Add a certificate to the WPACKET */
972
static int ssl_add_cert_to_wpacket(SSL_CONNECTION *s, WPACKET *pkt,
973
    X509 *x, int chain, int for_comp)
974
0
{
975
0
    int len;
976
0
    unsigned char *outbytes;
977
0
    int context = SSL_EXT_TLS1_3_CERTIFICATE;
978
979
0
    if (for_comp)
980
0
        context |= SSL_EXT_TLS1_3_CERTIFICATE_COMPRESSION;
981
982
0
    len = i2d_X509(x, NULL);
983
0
    if (len < 0) {
984
0
        if (!for_comp)
985
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
986
0
        return 0;
987
0
    }
988
0
    if (!WPACKET_sub_allocate_bytes_u24(pkt, len, &outbytes)
989
0
        || i2d_X509(x, &outbytes) != len) {
990
0
        if (!for_comp)
991
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
992
0
        return 0;
993
0
    }
994
995
0
    if ((SSL_CONNECTION_IS_TLS13(s) || for_comp)
996
0
        && !tls_construct_extensions(s, pkt, context, x, chain)) {
997
        /* SSLfatal() already called */
998
0
        return 0;
999
0
    }
1000
1001
0
    return 1;
1002
0
}
1003
1004
/* Add certificate chain to provided WPACKET */
1005
static int ssl_add_cert_chain(SSL_CONNECTION *s, WPACKET *pkt, CERT_PKEY *cpk, int for_comp)
1006
0
{
1007
0
    int i, chain_count;
1008
0
    X509 *x;
1009
0
    STACK_OF(X509) *extra_certs;
1010
0
    STACK_OF(X509) *chain = NULL;
1011
0
    X509_STORE *chain_store;
1012
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1013
1014
0
    if (cpk == NULL || cpk->x509 == NULL)
1015
0
        return 1;
1016
1017
0
    x = cpk->x509;
1018
1019
    /*
1020
     * If we have a certificate specific chain use it, else use parent ctx.
1021
     */
1022
0
    if (cpk->chain != NULL)
1023
0
        extra_certs = cpk->chain;
1024
0
    else
1025
0
        extra_certs = sctx->extra_certs;
1026
1027
0
    if ((s->mode & SSL_MODE_NO_AUTO_CHAIN) || extra_certs)
1028
0
        chain_store = NULL;
1029
0
    else if (s->cert->chain_store)
1030
0
        chain_store = s->cert->chain_store;
1031
0
    else
1032
0
        chain_store = sctx->cert_store;
1033
1034
0
    if (chain_store != NULL) {
1035
0
        X509_STORE_CTX *xs_ctx = X509_STORE_CTX_new_ex(sctx->libctx,
1036
0
            sctx->propq);
1037
1038
0
        if (xs_ctx == NULL) {
1039
0
            if (!for_comp)
1040
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1041
0
            return 0;
1042
0
        }
1043
0
        if (!X509_STORE_CTX_init(xs_ctx, chain_store, x, NULL)) {
1044
0
            X509_STORE_CTX_free(xs_ctx);
1045
0
            if (!for_comp)
1046
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_X509_LIB);
1047
0
            return 0;
1048
0
        }
1049
        /*
1050
         * It is valid for the chain not to be complete (because normally we
1051
         * don't include the root cert in the chain). Therefore we deliberately
1052
         * ignore the error return from this call. We're not actually verifying
1053
         * the cert - we're just building as much of the chain as we can
1054
         */
1055
0
        (void)X509_verify_cert(xs_ctx);
1056
        /* Don't leave errors in the queue */
1057
0
        ERR_clear_error();
1058
0
        chain = X509_STORE_CTX_get0_chain(xs_ctx);
1059
0
        i = ssl_security_cert_chain(s, chain, NULL);
1060
0
        if (i != 1) {
1061
#if 0
1062
            /* Dummy error calls so mkerr generates them */
1063
            ERR_raise(ERR_LIB_SSL, SSL_R_EE_KEY_TOO_SMALL);
1064
            ERR_raise(ERR_LIB_SSL, SSL_R_CA_KEY_TOO_SMALL);
1065
            ERR_raise(ERR_LIB_SSL, SSL_R_CA_MD_TOO_WEAK);
1066
#endif
1067
0
            X509_STORE_CTX_free(xs_ctx);
1068
0
            if (!for_comp)
1069
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1070
0
            return 0;
1071
0
        }
1072
0
        chain_count = sk_X509_num(chain);
1073
0
        for (i = 0; i < chain_count; i++) {
1074
0
            x = sk_X509_value(chain, i);
1075
1076
0
            if (!ssl_add_cert_to_wpacket(s, pkt, x, i, for_comp)) {
1077
                /* SSLfatal() already called */
1078
0
                X509_STORE_CTX_free(xs_ctx);
1079
0
                return 0;
1080
0
            }
1081
0
        }
1082
0
        X509_STORE_CTX_free(xs_ctx);
1083
0
    } else {
1084
0
        i = ssl_security_cert_chain(s, extra_certs, x);
1085
0
        if (i != 1) {
1086
0
            if (!for_comp)
1087
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, i);
1088
0
            return 0;
1089
0
        }
1090
0
        if (!ssl_add_cert_to_wpacket(s, pkt, x, 0, for_comp)) {
1091
            /* SSLfatal() already called */
1092
0
            return 0;
1093
0
        }
1094
0
        for (i = 0; i < sk_X509_num(extra_certs); i++) {
1095
0
            x = sk_X509_value(extra_certs, i);
1096
0
            if (!ssl_add_cert_to_wpacket(s, pkt, x, i + 1, for_comp)) {
1097
                /* SSLfatal() already called */
1098
0
                return 0;
1099
0
            }
1100
0
        }
1101
0
    }
1102
0
    return 1;
1103
0
}
1104
1105
EVP_PKEY *tls_get_peer_pkey(const SSL_CONNECTION *sc)
1106
0
{
1107
0
    if (sc->session->peer_rpk != NULL)
1108
0
        return sc->session->peer_rpk;
1109
0
    if (sc->session->peer != NULL)
1110
0
        return X509_get0_pubkey(sc->session->peer);
1111
0
    return NULL;
1112
0
}
1113
1114
int tls_process_rpk(SSL_CONNECTION *sc, PACKET *pkt, EVP_PKEY **peer_rpk)
1115
0
{
1116
0
    EVP_PKEY *pkey = NULL;
1117
0
    int ret = 0;
1118
0
    RAW_EXTENSION *rawexts = NULL;
1119
0
    PACKET extensions;
1120
0
    PACKET context;
1121
0
    unsigned long cert_len = 0, spki_len = 0;
1122
0
    const unsigned char *spki, *spkistart;
1123
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
1124
1125
    /*-
1126
     * ----------------------------
1127
     * TLS 1.3 Certificate message:
1128
     * ----------------------------
1129
     * https://datatracker.ietf.org/doc/html/rfc8446#section-4.4.2
1130
     *
1131
     *   enum {
1132
     *       X509(0),
1133
     *       RawPublicKey(2),
1134
     *       (255)
1135
     *   } CertificateType;
1136
     *
1137
     *   struct {
1138
     *       select (certificate_type) {
1139
     *           case RawPublicKey:
1140
     *             // From RFC 7250 ASN.1_subjectPublicKeyInfo
1141
     *             opaque ASN1_subjectPublicKeyInfo<1..2^24-1>;
1142
     *
1143
     *           case X509:
1144
     *             opaque cert_data<1..2^24-1>;
1145
     *       };
1146
     *       Extension extensions<0..2^16-1>;
1147
     *   } CertificateEntry;
1148
     *
1149
     *   struct {
1150
     *       opaque certificate_request_context<0..2^8-1>;
1151
     *       CertificateEntry certificate_list<0..2^24-1>;
1152
     *   } Certificate;
1153
     *
1154
     * The client MUST send a Certificate message if and only if the server
1155
     * has requested client authentication via a CertificateRequest message
1156
     * (Section 4.3.2).  If the server requests client authentication but no
1157
     * suitable certificate is available, the client MUST send a Certificate
1158
     * message containing no certificates (i.e., with the "certificate_list"
1159
     * field having length 0).
1160
     *
1161
     * ----------------------------
1162
     * TLS 1.2 Certificate message:
1163
     * ----------------------------
1164
     * https://datatracker.ietf.org/doc/html/rfc7250#section-3
1165
     *
1166
     *   opaque ASN.1Cert<1..2^24-1>;
1167
     *
1168
     *   struct {
1169
     *       select(certificate_type){
1170
     *
1171
     *            // certificate type defined in this document.
1172
     *            case RawPublicKey:
1173
     *              opaque ASN.1_subjectPublicKeyInfo<1..2^24-1>;
1174
     *
1175
     *           // X.509 certificate defined in RFC 5246
1176
     *           case X.509:
1177
     *             ASN.1Cert certificate_list<0..2^24-1>;
1178
     *
1179
     *           // Additional certificate type based on
1180
     *           // "TLS Certificate Types" subregistry
1181
     *       };
1182
     *   } Certificate;
1183
     *
1184
     * -------------
1185
     * Consequently:
1186
     * -------------
1187
     * After the (TLS 1.3 only) context octet string (1 byte length + data) the
1188
     * Certificate message has a 3-byte length that is zero in the client to
1189
     * server message when the client has no RPK to send.  In that case, there
1190
     * are no (TLS 1.3 only) per-certificate extensions either, because the
1191
     * [CertificateEntry] list is empty.
1192
     *
1193
     * In the server to client direction, or when the client had an RPK to send,
1194
     * the TLS 1.3 message just prepends the length of the RPK+extensions,
1195
     * while TLS <= 1.2 sends just the RPK (octet-string).
1196
     *
1197
     * The context must be zero-length in the server to client direction, and
1198
     * must match the value recorded in the certificate request in the client
1199
     * to server direction.
1200
     */
1201
0
    if (SSL_CONNECTION_IS_TLS13(sc)) {
1202
0
        if (!PACKET_get_length_prefixed_1(pkt, &context)) {
1203
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1204
0
            goto err;
1205
0
        }
1206
0
        if (sc->server) {
1207
0
            if (sc->pha_context == NULL) {
1208
0
                if (PACKET_remaining(&context) != 0) {
1209
0
                    SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1210
0
                    goto err;
1211
0
                }
1212
0
            } else {
1213
0
                if (!PACKET_equal(&context, sc->pha_context, sc->pha_context_len)) {
1214
0
                    SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1215
0
                    goto err;
1216
0
                }
1217
0
            }
1218
0
        } else {
1219
0
            if (PACKET_remaining(&context) != 0) {
1220
0
                SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
1221
0
                goto err;
1222
0
            }
1223
0
        }
1224
0
    }
1225
1226
0
    if (!PACKET_get_net_3(pkt, &cert_len)
1227
0
        || PACKET_remaining(pkt) != cert_len) {
1228
0
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1229
0
        goto err;
1230
0
    }
1231
1232
    /*
1233
     * The list length may be zero when there is no RPK.  In the case of TLS
1234
     * 1.2 this is actually the RPK length, which cannot be zero as specified,
1235
     * but that breaks the ability of the client to decline client auth. We
1236
     * overload the 0 RPK length to mean "no RPK".  This interpretation is
1237
     * also used some other (reference?) implementations, but is not supported
1238
     * by the verbatim RFC7250 text.
1239
     */
1240
0
    if (cert_len == 0)
1241
0
        return 1;
1242
1243
0
    if (SSL_CONNECTION_IS_TLS13(sc)) {
1244
        /*
1245
         * With TLS 1.3, a non-empty explicit-length RPK octet-string followed
1246
         * by a possibly empty extension block.
1247
         */
1248
0
        if (!PACKET_get_net_3(pkt, &spki_len)) {
1249
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1250
0
            goto err;
1251
0
        }
1252
0
        if (spki_len == 0) {
1253
            /* empty RPK */
1254
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_EMPTY_RAW_PUBLIC_KEY);
1255
0
            goto err;
1256
0
        }
1257
0
    } else {
1258
0
        spki_len = cert_len;
1259
0
    }
1260
1261
0
    if (!PACKET_get_bytes(pkt, &spki, spki_len)) {
1262
0
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1263
0
        goto err;
1264
0
    }
1265
0
    spkistart = spki;
1266
0
    if ((pkey = d2i_PUBKEY_ex(NULL, &spki, spki_len, sctx->libctx, sctx->propq)) == NULL
1267
0
        || spki != (spkistart + spki_len)) {
1268
0
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1269
0
        goto err;
1270
0
    }
1271
0
    if (EVP_PKEY_missing_parameters(pkey)) {
1272
0
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR,
1273
0
            SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1274
0
        goto err;
1275
0
    }
1276
1277
    /* Process the Extensions block */
1278
0
    if (SSL_CONNECTION_IS_TLS13(sc)) {
1279
0
        if (PACKET_remaining(pkt) != (cert_len - 3 - spki_len)) {
1280
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1281
0
            goto err;
1282
0
        }
1283
0
        if (!PACKET_as_length_prefixed_2(pkt, &extensions)
1284
0
            || PACKET_remaining(pkt) != 0) {
1285
0
            SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1286
0
            goto err;
1287
0
        }
1288
0
        if (!tls_collect_extensions(sc, &extensions, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1289
0
                &rawexts, NULL, 1)) {
1290
            /* SSLfatal already called */
1291
0
            goto err;
1292
0
        }
1293
        /* chain index is always zero and fin always 1 for RPK */
1294
0
        if (!tls_parse_all_extensions(sc, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1295
0
                rawexts, NULL, 0, 1)) {
1296
            /* SSLfatal already called */
1297
0
            goto err;
1298
0
        }
1299
0
    }
1300
0
    ret = 1;
1301
0
    if (peer_rpk != NULL) {
1302
0
        *peer_rpk = pkey;
1303
0
        pkey = NULL;
1304
0
    }
1305
1306
0
err:
1307
0
    OPENSSL_free(rawexts);
1308
0
    EVP_PKEY_free(pkey);
1309
0
    return ret;
1310
0
}
1311
1312
unsigned long tls_output_rpk(SSL_CONNECTION *sc, WPACKET *pkt, CERT_PKEY *cpk)
1313
0
{
1314
0
    int pdata_len = 0;
1315
0
    unsigned char *pdata = NULL;
1316
0
    const X509_PUBKEY *xpk = NULL;
1317
0
    unsigned long ret = 0;
1318
0
    X509 *x509 = NULL;
1319
1320
0
    if (cpk != NULL && cpk->x509 != NULL) {
1321
0
        x509 = cpk->x509;
1322
        /* Get the RPK from the certificate */
1323
0
        xpk = X509_get_X509_PUBKEY(cpk->x509);
1324
0
        if (xpk == NULL) {
1325
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1326
0
            goto err;
1327
0
        }
1328
0
        pdata_len = i2d_X509_PUBKEY(xpk, &pdata);
1329
0
    } else if (cpk != NULL && cpk->privatekey != NULL) {
1330
        /* Get the RPK from the private key */
1331
0
        pdata_len = i2d_PUBKEY(cpk->privatekey, &pdata);
1332
0
    } else {
1333
        /* The server RPK is not optional */
1334
0
        if (sc->server) {
1335
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1336
0
            goto err;
1337
0
        }
1338
        /* The client can send a zero length certificate list */
1339
0
        if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1340
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1341
0
            goto err;
1342
0
        }
1343
0
        return 1;
1344
0
    }
1345
1346
0
    if (pdata_len <= 0) {
1347
0
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1348
0
        goto err;
1349
0
    }
1350
1351
    /*
1352
     * TLSv1.2 is _just_ the raw public key
1353
     * TLSv1.3 includes extensions, so there's a length wrapper
1354
     */
1355
0
    if (SSL_CONNECTION_IS_TLS13(sc)) {
1356
0
        if (!WPACKET_start_sub_packet_u24(pkt)) {
1357
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1358
0
            goto err;
1359
0
        }
1360
0
    }
1361
1362
0
    if (!WPACKET_sub_memcpy_u24(pkt, pdata, pdata_len)) {
1363
0
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1364
0
        goto err;
1365
0
    }
1366
1367
0
    if (SSL_CONNECTION_IS_TLS13(sc)) {
1368
        /*
1369
         * Only send extensions relevant to raw public keys. Until such
1370
         * extensions are defined, this will be an empty set of extensions.
1371
         * |x509| may be NULL, which raw public-key extensions need to handle.
1372
         */
1373
0
        if (!tls_construct_extensions(sc, pkt, SSL_EXT_TLS1_3_RAW_PUBLIC_KEY,
1374
0
                x509, 0)) {
1375
            /* SSLfatal() already called */
1376
0
            goto err;
1377
0
        }
1378
0
        if (!WPACKET_close(pkt)) {
1379
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1380
0
            goto err;
1381
0
        }
1382
0
    }
1383
1384
0
    ret = 1;
1385
0
err:
1386
0
    OPENSSL_free(pdata);
1387
0
    return ret;
1388
0
}
1389
1390
unsigned long ssl3_output_cert_chain(SSL_CONNECTION *s, WPACKET *pkt,
1391
    CERT_PKEY *cpk, int for_comp)
1392
0
{
1393
0
    if (!WPACKET_start_sub_packet_u24(pkt)) {
1394
0
        if (!for_comp)
1395
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1396
0
        return 0;
1397
0
    }
1398
1399
0
    if (!ssl_add_cert_chain(s, pkt, cpk, for_comp))
1400
0
        return 0;
1401
1402
0
    if (!WPACKET_close(pkt)) {
1403
0
        if (!for_comp)
1404
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1405
0
        return 0;
1406
0
    }
1407
1408
0
    return 1;
1409
0
}
1410
1411
/*
1412
 * Tidy up after the end of a handshake. In the case of SCTP this may result
1413
 * in NBIO events. If |clearbufs| is set then init_buf and the wbio buffer is
1414
 * freed up as well.
1415
 */
1416
WORK_STATE tls_finish_handshake(SSL_CONNECTION *s, ossl_unused WORK_STATE wst,
1417
    int clearbufs, int stop)
1418
0
{
1419
0
    void (*cb)(const SSL *ssl, int type, int val) = NULL;
1420
0
    int cleanuphand = s->statem.cleanuphand;
1421
0
    SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
1422
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1423
1424
0
    if (clearbufs) {
1425
0
        if (!SSL_CONNECTION_IS_DTLS(s)
1426
#ifndef OPENSSL_NO_SCTP
1427
            /*
1428
             * RFC6083: SCTP provides a reliable and in-sequence transport service for DTLS
1429
             * messages that require it. Therefore, DTLS procedures for retransmissions
1430
             * MUST NOT be used.
1431
             * Hence the init_buf can be cleared when DTLS over SCTP as transport is used.
1432
             */
1433
            || BIO_dgram_is_sctp(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)))
1434
#endif
1435
0
        ) {
1436
            /*
1437
             * We don't do this in DTLS over UDP because we may still need the init_buf
1438
             * in case there are any unexpected retransmits
1439
             */
1440
0
            BUF_MEM_free(s->init_buf);
1441
0
            s->init_buf = NULL;
1442
0
        }
1443
1444
0
        if (!ssl_free_wbio_buffer(s)) {
1445
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1446
0
            return WORK_ERROR;
1447
0
        }
1448
0
        s->init_num = 0;
1449
0
    }
1450
1451
0
    if (SSL_CONNECTION_IS_TLS13(s) && !s->server
1452
0
        && s->post_handshake_auth == SSL_PHA_REQUESTED)
1453
0
        s->post_handshake_auth = SSL_PHA_EXT_SENT;
1454
1455
    /*
1456
     * Only set if there was a Finished message and this isn't after a TLSv1.3
1457
     * post handshake exchange
1458
     */
1459
0
    if (cleanuphand) {
1460
        /* skipped if we just sent a HelloRequest */
1461
0
        s->renegotiate = 0;
1462
0
        s->new_session = 0;
1463
0
        s->statem.cleanuphand = 0;
1464
0
        s->ext.ticket_expected = 0;
1465
1466
0
        ssl3_cleanup_key_block(s);
1467
1468
0
        if (s->server) {
1469
            /*
1470
             * In TLSv1.3 we update the cache as part of constructing the
1471
             * NewSessionTicket
1472
             */
1473
0
            if (!SSL_CONNECTION_IS_TLS13(s))
1474
0
                ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
1475
1476
            /* N.B. s->ctx may not equal s->session_ctx */
1477
0
            ssl_tsan_counter(sctx, &sctx->stats.sess_accept_good);
1478
0
            s->handshake_func = ossl_statem_accept;
1479
0
        } else {
1480
0
            if (SSL_CONNECTION_IS_TLS13(s)) {
1481
                /*
1482
                 * We encourage applications to only use TLSv1.3 tickets once,
1483
                 * so we remove this one from the cache.
1484
                 */
1485
0
                if ((s->session_ctx->session_cache_mode
1486
0
                        & SSL_SESS_CACHE_CLIENT)
1487
0
                    != 0)
1488
0
                    SSL_CTX_remove_session(s->session_ctx, s->session);
1489
0
            } else {
1490
                /*
1491
                 * In TLSv1.3 we update the cache as part of processing the
1492
                 * NewSessionTicket
1493
                 */
1494
0
                ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
1495
0
            }
1496
0
            if (s->hit)
1497
0
                ssl_tsan_counter(s->session_ctx,
1498
0
                    &s->session_ctx->stats.sess_hit);
1499
1500
0
            s->handshake_func = ossl_statem_connect;
1501
0
            ssl_tsan_counter(s->session_ctx,
1502
0
                &s->session_ctx->stats.sess_connect_good);
1503
0
        }
1504
1505
0
        if (SSL_CONNECTION_IS_DTLS(s)) {
1506
            /* done with handshaking */
1507
0
            s->d1->handshake_read_seq = 0;
1508
0
            s->d1->handshake_write_seq = 0;
1509
0
            s->d1->next_handshake_write_seq = 0;
1510
0
            dtls1_clear_received_buffer(s);
1511
0
        }
1512
0
    }
1513
1514
0
    if (s->info_callback != NULL)
1515
0
        cb = s->info_callback;
1516
0
    else if (sctx->info_callback != NULL)
1517
0
        cb = sctx->info_callback;
1518
1519
    /* The callback may expect us to not be in init at handshake done */
1520
0
    ossl_statem_set_in_init(s, 0);
1521
1522
0
    if (cb != NULL) {
1523
0
        if (cleanuphand
1524
0
            || !SSL_CONNECTION_IS_TLS13(s)
1525
0
            || SSL_IS_FIRST_HANDSHAKE(s))
1526
0
            cb(ssl, SSL_CB_HANDSHAKE_DONE, 1);
1527
0
    }
1528
1529
0
    if (!stop) {
1530
        /* If we've got more work to do we go back into init */
1531
0
        ossl_statem_set_in_init(s, 1);
1532
0
        return WORK_FINISHED_CONTINUE;
1533
0
    }
1534
1535
0
    return WORK_FINISHED_STOP;
1536
0
}
1537
1538
/*
1539
 * TLS 1.3 reserves handshake message type 0, so a HelloRequest must reach the
1540
 * state machine and be rejected there whenever TLS 1.3 is still possible.
1541
 *
1542
 * By the time a client reads a server handshake message, s->version is either
1543
 * the configured maximum for an initial pre-ServerHello handshake, or the
1544
 * already negotiated version after ServerHello or during renegotiation. Skip
1545
 * only when that version is below TLS 1.3.
1546
 */
1547
static int should_skip_hello_request(const SSL_CONNECTION *s)
1548
0
{
1549
0
    if (SSL_CONNECTION_IS_TLS13(s))
1550
0
        return 0;
1551
1552
0
    return s->version > 0 && s->version < TLS1_3_VERSION;
1553
0
}
1554
1555
int tls_get_message_header(SSL_CONNECTION *s, int *mt)
1556
0
{
1557
    /* s->init_num < SSL3_HM_HEADER_LENGTH */
1558
0
    int skip_message, i;
1559
0
    uint8_t recvd_type;
1560
0
    unsigned char *p;
1561
0
    size_t l, readbytes;
1562
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1563
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1564
1565
0
    p = (unsigned char *)s->init_buf->data;
1566
1567
0
    do {
1568
0
        while (s->init_num < SSL3_HM_HEADER_LENGTH) {
1569
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type,
1570
0
                &p[s->init_num],
1571
0
                SSL3_HM_HEADER_LENGTH - s->init_num,
1572
0
                0, &readbytes);
1573
0
            if (i <= 0) {
1574
0
                s->rwstate = SSL_READING;
1575
0
                return 0;
1576
0
            }
1577
0
            if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1578
                /*
1579
                 * A ChangeCipherSpec must be a single byte and may not occur
1580
                 * in the middle of a handshake message.
1581
                 */
1582
0
                if (s->init_num != 0 || readbytes != 1 || p[0] != SSL3_MT_CCS) {
1583
0
                    SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1584
0
                        SSL_R_BAD_CHANGE_CIPHER_SPEC);
1585
0
                    return 0;
1586
0
                }
1587
0
                if (s->statem.hand_state == TLS_ST_BEFORE
1588
0
                    && (s->s3.flags & TLS1_FLAGS_STATELESS) != 0) {
1589
                    /*
1590
                     * We are stateless and we received a CCS. Probably this is
1591
                     * from a client between the first and second ClientHellos.
1592
                     * We should ignore this, but return an error because we do
1593
                     * not return success until we see the second ClientHello
1594
                     * with a valid cookie.
1595
                     */
1596
0
                    return 0;
1597
0
                }
1598
0
                s->s3.tmp.message_type = *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1599
0
                s->init_num = readbytes - 1;
1600
0
                s->init_msg = s->init_buf->data;
1601
0
                s->s3.tmp.message_size = readbytes;
1602
0
                return 1;
1603
0
            } else if (recvd_type != SSL3_RT_HANDSHAKE) {
1604
0
                SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1605
0
                    SSL_R_CCS_RECEIVED_EARLY);
1606
0
                return 0;
1607
0
            }
1608
0
            s->init_num += readbytes;
1609
0
        }
1610
1611
0
        skip_message = 0;
1612
0
        if (!s->server)
1613
0
            if (s->statem.hand_state != TLS_ST_OK
1614
0
                && p[0] == SSL3_MT_HELLO_REQUEST
1615
0
                && should_skip_hello_request(s))
1616
                /*
1617
                 * The server may always send 'Hello Request' messages --
1618
                 * we are doing a handshake anyway now, so ignore them if
1619
                 * their format is correct. Does not count for 'Finished'
1620
                 * MAC.
1621
                 */
1622
0
                if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1623
0
                    s->init_num = 0;
1624
0
                    skip_message = 1;
1625
1626
0
                    if (s->msg_callback)
1627
0
                        s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1628
0
                            p, SSL3_HM_HEADER_LENGTH, ussl,
1629
0
                            s->msg_callback_arg);
1630
0
                }
1631
0
    } while (skip_message);
1632
    /* s->init_num == SSL3_HM_HEADER_LENGTH */
1633
1634
0
    *mt = *p;
1635
0
    s->s3.tmp.message_type = *(p++);
1636
1637
0
    n2l3(p, l);
1638
    /* BUF_MEM_grow takes an 'int' parameter */
1639
0
    if (l > (INT_MAX - SSL3_HM_HEADER_LENGTH)) {
1640
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
1641
0
        return 0;
1642
0
    }
1643
0
    s->s3.tmp.message_size = l;
1644
1645
0
    s->init_msg = s->init_buf->data + SSL3_HM_HEADER_LENGTH;
1646
0
    s->init_num = 0;
1647
1648
0
    return 1;
1649
0
}
1650
1651
static int grow_init_buf(SSL_CONNECTION *s, size_t size)
1652
0
{
1653
1654
0
    size_t msg_offset = (char *)s->init_msg - s->init_buf->data;
1655
1656
0
    if (!BUF_MEM_grow_clean(s->init_buf, size))
1657
0
        return 0;
1658
1659
0
    if (size < msg_offset)
1660
0
        return 0;
1661
1662
0
    s->init_msg = s->init_buf->data + msg_offset;
1663
1664
0
    return 1;
1665
0
}
1666
1667
int tls_get_message_body(SSL_CONNECTION *s, size_t *len)
1668
0
{
1669
0
    size_t toread, readbytes;
1670
0
    unsigned char *p;
1671
0
    int i;
1672
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1673
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1674
1675
0
    if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
1676
        /* We've already read everything in */
1677
0
        *len = (unsigned long)s->init_num;
1678
0
        return 1;
1679
0
    }
1680
1681
0
    toread = s->s3.tmp.message_size - s->init_num;
1682
0
    while (toread > 0) {
1683
0
        size_t chunk = toread > SSL3_RT_MAX_PLAIN_LENGTH ? SSL3_RT_MAX_PLAIN_LENGTH : toread;
1684
1685
        /*
1686
         * We incrementally allocate the buffer to guard against the peer
1687
         * claiming a very large message size and then not sending it.
1688
         */
1689
0
        if (!grow_init_buf(s, s->init_num + chunk + SSL3_HM_HEADER_LENGTH)) {
1690
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
1691
0
            return 0;
1692
0
        }
1693
1694
        /* init_msg location can change after grow_init_buf */
1695
0
        p = s->init_msg;
1696
0
        i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1697
0
            &p[s->init_num], chunk, 0, &readbytes);
1698
0
        if (i <= 0) {
1699
0
            s->rwstate = SSL_READING;
1700
0
            *len = 0;
1701
0
            return 0;
1702
0
        }
1703
0
        s->init_num += readbytes;
1704
0
        toread -= readbytes;
1705
0
    }
1706
1707
    /*
1708
     * If receiving Finished, record MAC of prior handshake messages for
1709
     * Finished verification.
1710
     */
1711
0
    if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
1712
        /* SSLfatal() already called */
1713
0
        *len = 0;
1714
0
        return 0;
1715
0
    }
1716
1717
    /*
1718
     * We defer feeding in the HRR until later. We'll do it as part of
1719
     * processing the message
1720
     * The TLsv1.3 handshake transcript stops at the ClientFinished
1721
     * message.
1722
     */
1723
0
#define SERVER_HELLO_RANDOM_OFFSET (SSL3_HM_HEADER_LENGTH + 2)
1724
    /* KeyUpdate and NewSessionTicket do not need to be added */
1725
0
    if (!SSL_CONNECTION_IS_TLS13(s)
1726
0
        || (s->s3.tmp.message_type != SSL3_MT_NEWSESSION_TICKET
1727
0
            && s->s3.tmp.message_type != SSL3_MT_KEY_UPDATE)) {
1728
0
        if (s->s3.tmp.message_type != SSL3_MT_SERVER_HELLO
1729
0
            || s->init_num < SERVER_HELLO_RANDOM_OFFSET + SSL3_RANDOM_SIZE
1730
0
            || memcmp(hrrrandom,
1731
0
                   s->init_buf->data + SERVER_HELLO_RANDOM_OFFSET,
1732
0
                   SSL3_RANDOM_SIZE)
1733
0
                != 0) {
1734
0
            if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1735
0
                    s->init_num + SSL3_HM_HEADER_LENGTH)) {
1736
                /* SSLfatal() already called */
1737
0
                *len = 0;
1738
0
                return 0;
1739
0
            }
1740
0
        }
1741
0
    }
1742
0
    if (s->msg_callback)
1743
0
        s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->init_buf->data,
1744
0
            (size_t)s->init_num + SSL3_HM_HEADER_LENGTH, ussl,
1745
0
            s->msg_callback_arg);
1746
1747
0
    *len = s->init_num;
1748
0
    return 1;
1749
0
}
1750
1751
static const X509ERR2ALERT x509table[] = {
1752
    { X509_V_ERR_APPLICATION_VERIFICATION, SSL_AD_HANDSHAKE_FAILURE },
1753
    { X509_V_ERR_CA_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE },
1754
    { X509_V_ERR_EC_KEY_EXPLICIT_PARAMS, SSL_AD_BAD_CERTIFICATE },
1755
    { X509_V_ERR_CA_MD_TOO_WEAK, SSL_AD_BAD_CERTIFICATE },
1756
    { X509_V_ERR_CERT_CHAIN_TOO_LONG, SSL_AD_UNKNOWN_CA },
1757
    { X509_V_ERR_CERT_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED },
1758
    { X509_V_ERR_CERT_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE },
1759
    { X509_V_ERR_CERT_REJECTED, SSL_AD_BAD_CERTIFICATE },
1760
    { X509_V_ERR_CERT_REVOKED, SSL_AD_CERTIFICATE_REVOKED },
1761
    { X509_V_ERR_CERT_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR },
1762
    { X509_V_ERR_CERT_UNTRUSTED, SSL_AD_BAD_CERTIFICATE },
1763
    { X509_V_ERR_CRL_HAS_EXPIRED, SSL_AD_CERTIFICATE_EXPIRED },
1764
    { X509_V_ERR_CRL_NOT_YET_VALID, SSL_AD_BAD_CERTIFICATE },
1765
    { X509_V_ERR_CRL_SIGNATURE_FAILURE, SSL_AD_DECRYPT_ERROR },
1766
    { X509_V_ERR_DANE_NO_MATCH, SSL_AD_BAD_CERTIFICATE },
1767
    { X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT, SSL_AD_UNKNOWN_CA },
1768
    { X509_V_ERR_EE_KEY_TOO_SMALL, SSL_AD_BAD_CERTIFICATE },
1769
    { X509_V_ERR_EMAIL_MISMATCH, SSL_AD_BAD_CERTIFICATE },
1770
    { X509_V_ERR_ERROR_IN_CERT_NOT_AFTER_FIELD, SSL_AD_BAD_CERTIFICATE },
1771
    { X509_V_ERR_ERROR_IN_CERT_NOT_BEFORE_FIELD, SSL_AD_BAD_CERTIFICATE },
1772
    { X509_V_ERR_ERROR_IN_CRL_LAST_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE },
1773
    { X509_V_ERR_ERROR_IN_CRL_NEXT_UPDATE_FIELD, SSL_AD_BAD_CERTIFICATE },
1774
    { X509_V_ERR_HOSTNAME_MISMATCH, SSL_AD_BAD_CERTIFICATE },
1775
    { X509_V_ERR_INVALID_CA, SSL_AD_UNKNOWN_CA },
1776
    { X509_V_ERR_INVALID_CALL, SSL_AD_INTERNAL_ERROR },
1777
    { X509_V_ERR_INVALID_PURPOSE, SSL_AD_UNSUPPORTED_CERTIFICATE },
1778
    { X509_V_ERR_IP_ADDRESS_MISMATCH, SSL_AD_BAD_CERTIFICATE },
1779
    { X509_V_ERR_OUT_OF_MEM, SSL_AD_INTERNAL_ERROR },
1780
    { X509_V_ERR_PATH_LENGTH_EXCEEDED, SSL_AD_UNKNOWN_CA },
1781
    { X509_V_ERR_SELF_SIGNED_CERT_IN_CHAIN, SSL_AD_UNKNOWN_CA },
1782
    { X509_V_ERR_STORE_LOOKUP, SSL_AD_INTERNAL_ERROR },
1783
    { X509_V_ERR_UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY, SSL_AD_BAD_CERTIFICATE },
1784
    { X509_V_ERR_UNABLE_TO_DECRYPT_CERT_SIGNATURE, SSL_AD_BAD_CERTIFICATE },
1785
    { X509_V_ERR_UNABLE_TO_DECRYPT_CRL_SIGNATURE, SSL_AD_BAD_CERTIFICATE },
1786
    { X509_V_ERR_UNABLE_TO_GET_CRL, SSL_AD_UNKNOWN_CA },
1787
    { X509_V_ERR_UNABLE_TO_GET_CRL_ISSUER, SSL_AD_UNKNOWN_CA },
1788
    { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT, SSL_AD_UNKNOWN_CA },
1789
    { X509_V_ERR_UNABLE_TO_GET_ISSUER_CERT_LOCALLY, SSL_AD_UNKNOWN_CA },
1790
    { X509_V_ERR_UNABLE_TO_VERIFY_LEAF_SIGNATURE, SSL_AD_UNKNOWN_CA },
1791
    { X509_V_ERR_UNSPECIFIED, SSL_AD_INTERNAL_ERROR },
1792
1793
    /* Last entry; return this if we don't find the value above. */
1794
    { X509_V_OK, SSL_AD_CERTIFICATE_UNKNOWN }
1795
};
1796
1797
int ssl_x509err2alert(int x509err)
1798
0
{
1799
0
    const X509ERR2ALERT *tp;
1800
1801
0
    for (tp = x509table; tp->x509err != X509_V_OK; ++tp)
1802
0
        if (tp->x509err == x509err)
1803
0
            break;
1804
0
    return tp->alert;
1805
0
}
1806
1807
int ssl_allow_compression(SSL_CONNECTION *s)
1808
0
{
1809
0
    if (s->options & SSL_OP_NO_COMPRESSION)
1810
0
        return 0;
1811
0
    return ssl_security(s, SSL_SECOP_COMPRESSION, 0, 0, NULL);
1812
0
}
1813
1814
/*
1815
 * SSL/TLS/DTLS version comparison
1816
 *
1817
 * Returns
1818
 *      0 if versiona is equal to versionb
1819
 *      1 if versiona is greater than versionb
1820
 *     -1 if versiona is less than versionb
1821
 */
1822
int ssl_version_cmp(const SSL_CONNECTION *s, int versiona, int versionb)
1823
0
{
1824
0
    int dtls = SSL_CONNECTION_IS_DTLS(s);
1825
1826
0
    if (versiona == versionb)
1827
0
        return 0;
1828
0
    if (!dtls)
1829
0
        return versiona < versionb ? -1 : 1;
1830
0
    return DTLS_VERSION_LT(versiona, versionb) ? -1 : 1;
1831
0
}
1832
1833
typedef struct {
1834
    int version;
1835
    const SSL_METHOD *(*cmeth)(void);
1836
    const SSL_METHOD *(*smeth)(void);
1837
} version_info;
1838
1839
#if TLS_MAX_VERSION_INTERNAL != TLS1_3_VERSION
1840
#error Code needs update for TLS_method() support beyond TLS1_3_VERSION.
1841
#endif
1842
1843
/* Must be in order high to low */
1844
static const version_info tls_version_table[] = {
1845
#ifndef OPENSSL_NO_TLS1_3
1846
    { TLS1_3_VERSION, tlsv1_3_client_method, tlsv1_3_server_method },
1847
#else
1848
    { TLS1_3_VERSION, NULL, NULL },
1849
#endif
1850
#ifndef OPENSSL_NO_TLS1_2
1851
    { TLS1_2_VERSION, tlsv1_2_client_method, tlsv1_2_server_method },
1852
#else
1853
    { TLS1_2_VERSION, NULL, NULL },
1854
#endif
1855
#ifndef OPENSSL_NO_TLS1_1
1856
    { TLS1_1_VERSION, tlsv1_1_client_method, tlsv1_1_server_method },
1857
#else
1858
    { TLS1_1_VERSION, NULL, NULL },
1859
#endif
1860
#ifndef OPENSSL_NO_TLS1
1861
    { TLS1_VERSION, tlsv1_client_method, tlsv1_server_method },
1862
#else
1863
    { TLS1_VERSION, NULL, NULL },
1864
#endif
1865
    { 0, NULL, NULL },
1866
};
1867
1868
#if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
1869
#error Code needs update for DTLS_method() support beyond DTLS1_2_VERSION.
1870
#endif
1871
1872
/* Must be in order high to low */
1873
static const version_info dtls_version_table[] = {
1874
#ifndef OPENSSL_NO_DTLS1_2
1875
    { DTLS1_2_VERSION, dtlsv1_2_client_method, dtlsv1_2_server_method },
1876
#else
1877
    { DTLS1_2_VERSION, NULL, NULL },
1878
#endif
1879
#ifndef OPENSSL_NO_DTLS1
1880
    { DTLS1_VERSION, dtlsv1_client_method, dtlsv1_server_method },
1881
    { DTLS1_BAD_VER, dtls_bad_ver_client_method, NULL },
1882
#else
1883
    { DTLS1_VERSION, NULL, NULL },
1884
    { DTLS1_BAD_VER, NULL, NULL },
1885
#endif
1886
    { 0, NULL, NULL },
1887
};
1888
1889
/*
1890
 * ssl_method_error - Check whether an SSL_METHOD is enabled.
1891
 *
1892
 * @s: The SSL handle for the candidate method
1893
 * @method: the intended method.
1894
 *
1895
 * Returns 0 on success, or an SSL error reason on failure.
1896
 */
1897
static int ssl_method_error(const SSL_CONNECTION *s, const SSL_METHOD *method)
1898
0
{
1899
0
    int version = method->version;
1900
1901
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)
1902
0
        return SSL_R_VERSION_TOO_LOW;
1903
1904
0
    if (s->max_proto_version != 0 && ssl_version_cmp(s, version, s->max_proto_version) > 0)
1905
0
        return SSL_R_VERSION_TOO_HIGH;
1906
1907
0
    if ((s->options & method->mask) != 0)
1908
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
1909
0
    if ((method->flags & SSL_METHOD_NO_SUITEB) != 0 && tls1_suiteb(s))
1910
0
        return SSL_R_AT_LEAST_TLS_1_2_NEEDED_IN_SUITEB_MODE;
1911
1912
0
    return 0;
1913
0
}
1914
1915
/*
1916
 * Only called by servers. Returns 1 if the server has a TLSv1.3 capable
1917
 * certificate type, or has PSK or a certificate callback configured, or has
1918
 * a servername callback configure. Otherwise returns 0.
1919
 */
1920
static int is_tls13_capable(const SSL_CONNECTION *s)
1921
0
{
1922
0
    size_t i;
1923
0
    int curve;
1924
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1925
1926
0
    if (!ossl_assert(sctx != NULL) || !ossl_assert(s->session_ctx != NULL))
1927
0
        return 0;
1928
1929
    /*
1930
     * A servername callback can change the available certs, so if a servername
1931
     * cb is set then we just assume TLSv1.3 will be ok
1932
     */
1933
0
    if (sctx->ext.servername_cb != NULL
1934
0
        || s->session_ctx->ext.servername_cb != NULL)
1935
0
        return 1;
1936
1937
0
#ifndef OPENSSL_NO_PSK
1938
0
    if (s->psk_server_callback != NULL)
1939
0
        return 1;
1940
0
#endif
1941
1942
0
    if (s->psk_find_session_cb != NULL || s->cert->cert_cb != NULL)
1943
0
        return 1;
1944
1945
    /* All provider-based sig algs are required to support at least TLS1.3 */
1946
0
    for (i = 0; i < s->ssl_pkey_num; i++) {
1947
        /* Skip over certs disallowed for TLSv1.3 */
1948
0
        switch (i) {
1949
0
        case SSL_PKEY_DSA_SIGN:
1950
0
        case SSL_PKEY_GOST01:
1951
0
        case SSL_PKEY_GOST12_256:
1952
0
        case SSL_PKEY_GOST12_512:
1953
0
            continue;
1954
0
        default:
1955
0
            break;
1956
0
        }
1957
0
        if (!ssl_has_cert(s, (int)i))
1958
0
            continue;
1959
0
        if (i != SSL_PKEY_ECC)
1960
0
            return 1;
1961
        /*
1962
         * Prior to TLSv1.3 sig algs allowed any curve to be used. TLSv1.3 is
1963
         * more restrictive so check that our sig algs are consistent with this
1964
         * EC cert. See section 4.2.3 of RFC8446.
1965
         */
1966
0
        curve = ssl_get_EC_curve_nid(s->cert->pkeys[SSL_PKEY_ECC].privatekey);
1967
0
        if (tls_check_sigalg_curve(s, curve))
1968
0
            return 1;
1969
0
    }
1970
1971
0
    return 0;
1972
0
}
1973
1974
/*
1975
 * ssl_version_supported - Check that the specified `version` is supported by
1976
 * `SSL *` instance
1977
 *
1978
 * @s: The SSL handle for the candidate method
1979
 * @version: Protocol version to test against
1980
 *
1981
 * Returns 1 when supported, otherwise 0
1982
 */
1983
int ssl_version_supported(const SSL_CONNECTION *s, int version,
1984
    const SSL_METHOD **meth)
1985
0
{
1986
0
    const version_info *vent;
1987
0
    const version_info *table;
1988
1989
0
    switch (SSL_CONNECTION_GET_SSL(s)->method->version) {
1990
0
    default:
1991
        /* Version should match method version for non-ANY method */
1992
0
        return ssl_version_cmp(s, version, s->version) == 0;
1993
0
    case TLS_ANY_VERSION:
1994
0
        table = tls_version_table;
1995
0
        break;
1996
0
    case DTLS_ANY_VERSION:
1997
0
        table = dtls_version_table;
1998
0
        break;
1999
0
    }
2000
2001
0
    for (vent = table;
2002
0
        vent->version != 0 && ssl_version_cmp(s, version, vent->version) <= 0;
2003
0
        ++vent) {
2004
0
        const SSL_METHOD *(*thismeth)(void) = s->server ? vent->smeth
2005
0
                                                        : vent->cmeth;
2006
2007
0
        if (thismeth != NULL
2008
0
            && ssl_version_cmp(s, version, vent->version) == 0
2009
0
            && ssl_method_error(s, thismeth()) == 0
2010
0
            && (!s->server
2011
0
                || version != TLS1_3_VERSION
2012
0
                || is_tls13_capable(s))) {
2013
0
            if (meth != NULL)
2014
0
                *meth = thismeth();
2015
0
            return 1;
2016
0
        }
2017
0
    }
2018
0
    return 0;
2019
0
}
2020
2021
/*
2022
 * ssl_check_version_downgrade - In response to RFC7507 SCSV version
2023
 * fallback indication from a client check whether we're using the highest
2024
 * supported protocol version.
2025
 *
2026
 * @s server SSL handle.
2027
 *
2028
 * Returns 1 when using the highest enabled version, 0 otherwise.
2029
 */
2030
int ssl_check_version_downgrade(SSL_CONNECTION *s)
2031
0
{
2032
0
    const version_info *vent;
2033
0
    const version_info *table;
2034
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2035
2036
    /*
2037
     * Check that the current protocol is the highest enabled version
2038
     * (according to ssl->defltmethod, as version negotiation may have changed
2039
     * s->method).
2040
     */
2041
0
    if (s->version == ssl->defltmeth->version)
2042
0
        return 1;
2043
2044
    /*
2045
     * Apparently we're using a version-flexible SSL_METHOD (not at its
2046
     * highest protocol version).
2047
     */
2048
0
    if (ssl->defltmeth->version == TLS_method()->version)
2049
0
        table = tls_version_table;
2050
0
    else if (ssl->defltmeth->version == DTLS_method()->version)
2051
0
        table = dtls_version_table;
2052
0
    else {
2053
        /* Unexpected state; fail closed. */
2054
0
        return 0;
2055
0
    }
2056
2057
0
    for (vent = table; vent->version != 0; ++vent) {
2058
0
        if (vent->smeth != NULL && ssl_method_error(s, vent->smeth()) == 0)
2059
0
            return s->version == vent->version;
2060
0
    }
2061
0
    return 0;
2062
0
}
2063
2064
/*
2065
 * ssl_set_version_bound - set an upper or lower bound on the supported (D)TLS
2066
 * protocols, provided the initial (D)TLS method is version-flexible.  This
2067
 * function sanity-checks the proposed value and makes sure the method is
2068
 * version-flexible, then sets the limit if all is well.
2069
 *
2070
 * @method_version: The version of the current SSL_METHOD.
2071
 * @version: the intended limit.
2072
 * @bound: pointer to limit to be updated.
2073
 *
2074
 * Returns 1 on success, 0 on failure.
2075
 */
2076
int ssl_set_version_bound(int method_version, int version, int *bound)
2077
0
{
2078
0
    int valid_tls;
2079
0
    int valid_dtls;
2080
2081
0
    if (version == 0) {
2082
0
        *bound = version;
2083
0
        return 1;
2084
0
    }
2085
2086
0
    valid_tls = version > SSL3_VERSION && version <= TLS_MAX_VERSION_INTERNAL;
2087
0
    valid_dtls =
2088
        /* We support client side pre-standardisation version of DTLS */
2089
0
        (version == DTLS1_BAD_VER)
2090
0
        || (DTLS_VERSION_LE(version, DTLS_MAX_VERSION_INTERNAL)
2091
0
            && DTLS_VERSION_GE(version, DTLS1_VERSION));
2092
2093
0
    if (!valid_tls && !valid_dtls)
2094
0
        return 0;
2095
2096
    /*-
2097
     * Restrict TLS methods to TLS protocol versions.
2098
     * Restrict DTLS methods to DTLS protocol versions.
2099
     * Note, DTLS version numbers are decreasing, use comparison macros.
2100
     *
2101
     * Note that for both lower-bounds we use explicit versions, not
2102
     * (D)TLS_MIN_VERSION.  This is because we don't want to break user
2103
     * configurations.  If the MIN (supported) version ever rises, the user's
2104
     * "floor" remains valid even if no longer available.  We don't expect the
2105
     * MAX ceiling to ever get lower, so making that variable makes sense.
2106
     *
2107
     * We ignore attempts to set bounds on version-inflexible methods,
2108
     * returning success.
2109
     */
2110
0
    switch (method_version) {
2111
0
    default:
2112
0
        break;
2113
2114
0
    case TLS_ANY_VERSION:
2115
0
        if (valid_tls)
2116
0
            *bound = version;
2117
0
        break;
2118
2119
0
    case DTLS_ANY_VERSION:
2120
0
        if (valid_dtls)
2121
0
            *bound = version;
2122
0
        break;
2123
0
    }
2124
0
    return 1;
2125
0
}
2126
2127
static void check_for_downgrade(SSL_CONNECTION *s, int vers, DOWNGRADE *dgrd)
2128
0
{
2129
0
    if (vers == TLS1_2_VERSION
2130
0
        && ssl_version_supported(s, TLS1_3_VERSION, NULL)) {
2131
0
        *dgrd = DOWNGRADE_TO_1_2;
2132
0
    } else if (!SSL_CONNECTION_IS_DTLS(s)
2133
0
        && vers < TLS1_2_VERSION
2134
        /*
2135
         * We need to ensure that a server that disables TLSv1.2
2136
         * (creating a hole between TLSv1.3 and TLSv1.1) can still
2137
         * complete handshakes with clients that support TLSv1.2 and
2138
         * below. Therefore we do not enable the sentinel if TLSv1.3 is
2139
         * enabled and TLSv1.2 is not.
2140
         */
2141
0
        && ssl_version_supported(s, TLS1_2_VERSION, NULL)) {
2142
0
        *dgrd = DOWNGRADE_TO_1_1;
2143
0
    } else {
2144
0
        *dgrd = DOWNGRADE_NONE;
2145
0
    }
2146
0
}
2147
2148
/*
2149
 * ssl_choose_server_version - Choose server (D)TLS version.  Called when the
2150
 * client HELLO is received to select the final server protocol version and
2151
 * the version specific method.
2152
 *
2153
 * @s: server SSL handle.
2154
 *
2155
 * Returns 0 on success or an SSL error reason number on failure.
2156
 */
2157
int ssl_choose_server_version(SSL_CONNECTION *s, CLIENTHELLO_MSG *hello,
2158
    DOWNGRADE *dgrd)
2159
0
{
2160
    /*-
2161
     * With version-flexible methods we have an initial state with:
2162
     *
2163
     *   s->method->version == (D)TLS_ANY_VERSION,
2164
     *   s->version == (D)TLS_MAX_VERSION_INTERNAL.
2165
     *
2166
     * So we detect version-flexible methods via the method version, not the
2167
     * handle version.
2168
     */
2169
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2170
0
    int server_version = ssl->method->version;
2171
0
    int client_version = hello->legacy_version;
2172
0
    const version_info *vent;
2173
0
    const version_info *table;
2174
0
    int disabled = 0;
2175
0
    RAW_EXTENSION *suppversions;
2176
2177
0
    s->client_version = client_version;
2178
2179
0
    switch (server_version) {
2180
0
    default:
2181
0
        if (!SSL_CONNECTION_IS_TLS13(s)) {
2182
0
            if (ssl_version_cmp(s, client_version, s->version) < 0)
2183
0
                return SSL_R_WRONG_SSL_VERSION;
2184
0
            *dgrd = DOWNGRADE_NONE;
2185
            /*
2186
             * If this SSL handle is not from a version flexible method we don't
2187
             * (and never did) check min/max FIPS or Suite B constraints.  Hope
2188
             * that's OK.  It is up to the caller to not choose fixed protocol
2189
             * versions they don't want.  If not, then easy to fix, just return
2190
             * ssl_method_error(s, s->method)
2191
             */
2192
0
            return 0;
2193
0
        }
2194
        /*
2195
         * Fall through if we are TLSv1.3 already (this means we must be after
2196
         * a HelloRetryRequest
2197
         */
2198
        /* fall thru */
2199
0
    case TLS_ANY_VERSION:
2200
0
        table = tls_version_table;
2201
0
        break;
2202
0
    case DTLS_ANY_VERSION:
2203
0
        table = dtls_version_table;
2204
0
        break;
2205
0
    }
2206
2207
0
    suppversions = &hello->pre_proc_exts[TLSEXT_IDX_supported_versions];
2208
2209
0
#ifndef OPENSSL_NO_ECH
2210
    /*
2211
     * Check we're dealing with a TLSv1.3 connection when ECH has
2212
     * succeeded, and not with a smuggled earlier version ClientHello
2213
     * (which could be a form of attack).
2214
     * This bit checks there is a supported version present, a little
2215
     * bit further below, we check that that version is TLSv1.3
2216
     */
2217
0
    if (!suppversions->present && s->ext.ech.success == 1)
2218
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
2219
0
#endif
2220
2221
    /* If we did an HRR then supported versions is mandatory */
2222
0
    if (!suppversions->present && s->hello_retry_request != SSL_HRR_NONE)
2223
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
2224
2225
0
    if (suppversions->present && !SSL_CONNECTION_IS_DTLS(s)) {
2226
0
        unsigned int candidate_vers = 0;
2227
0
        unsigned int best_vers = 0;
2228
0
        const SSL_METHOD *best_method = NULL;
2229
0
        PACKET versionslist;
2230
2231
0
        suppversions->parsed = 1;
2232
2233
0
        if (!PACKET_as_length_prefixed_1(&suppversions->data, &versionslist)) {
2234
            /* Trailing or invalid data? */
2235
0
            return SSL_R_LENGTH_MISMATCH;
2236
0
        }
2237
2238
        /*
2239
         * The TLSv1.3 spec says the client MUST set this to TLS1_2_VERSION.
2240
         * The spec only requires servers to check that it isn't SSLv3:
2241
         * "Any endpoint receiving a Hello message with
2242
         * ClientHello.legacy_version or ServerHello.legacy_version set to
2243
         * 0x0300 MUST abort the handshake with a "protocol_version" alert."
2244
         * We are slightly stricter and require that it isn't SSLv3 or lower.
2245
         * We tolerate TLSv1 and TLSv1.1.
2246
         */
2247
0
        if (client_version <= SSL3_VERSION)
2248
0
            return SSL_R_BAD_LEGACY_VERSION;
2249
2250
0
        while (PACKET_get_net_2(&versionslist, &candidate_vers)) {
2251
0
            if (ssl_version_cmp(s, candidate_vers, best_vers) <= 0)
2252
0
                continue;
2253
0
            if (ssl_version_supported(s, candidate_vers, &best_method))
2254
0
                best_vers = candidate_vers;
2255
0
        }
2256
0
        if (PACKET_remaining(&versionslist) != 0) {
2257
            /* Trailing data? */
2258
0
            return SSL_R_LENGTH_MISMATCH;
2259
0
        }
2260
2261
0
        if (best_vers > 0) {
2262
0
#ifndef OPENSSL_NO_ECH
2263
            /* ECH needs TLSV1.3 also */
2264
0
            if (s->ext.ech.success == 1 && best_vers != TLS1_3_VERSION)
2265
0
                return SSL_R_UNSUPPORTED_PROTOCOL;
2266
0
#endif
2267
0
            if (s->hello_retry_request != SSL_HRR_NONE) {
2268
                /*
2269
                 * This is after a HelloRetryRequest so we better check that we
2270
                 * negotiated TLSv1.3
2271
                 */
2272
0
                if (best_vers != TLS1_3_VERSION)
2273
0
                    return SSL_R_UNSUPPORTED_PROTOCOL;
2274
0
                return 0;
2275
0
            }
2276
0
            check_for_downgrade(s, best_vers, dgrd);
2277
0
            s->version = best_vers;
2278
0
            ssl->method = best_method;
2279
0
            if (!ssl_set_record_protocol_version(s, best_vers))
2280
0
                return ERR_R_INTERNAL_ERROR;
2281
2282
0
            return 0;
2283
0
        }
2284
0
        return SSL_R_UNSUPPORTED_PROTOCOL;
2285
0
    }
2286
2287
    /*
2288
     * If the supported versions extension isn't present, then the highest
2289
     * version we can negotiate is TLSv1.2
2290
     */
2291
0
    if (ssl_version_cmp(s, client_version, TLS1_3_VERSION) >= 0)
2292
0
        client_version = TLS1_2_VERSION;
2293
2294
    /*
2295
     * No supported versions extension, so we just use the version supplied in
2296
     * the ClientHello.
2297
     */
2298
0
    for (vent = table; vent->version != 0; ++vent) {
2299
0
        const SSL_METHOD *method;
2300
2301
0
        if (vent->smeth == NULL || ssl_version_cmp(s, client_version, vent->version) < 0)
2302
0
            continue;
2303
0
        method = vent->smeth();
2304
0
        if (ssl_method_error(s, method) == 0) {
2305
0
            check_for_downgrade(s, vent->version, dgrd);
2306
0
            s->version = vent->version;
2307
0
            ssl->method = method;
2308
0
            if (!ssl_set_record_protocol_version(s, s->version))
2309
0
                return ERR_R_INTERNAL_ERROR;
2310
2311
0
            return 0;
2312
0
        }
2313
0
        disabled = 1;
2314
0
    }
2315
0
    return disabled ? SSL_R_UNSUPPORTED_PROTOCOL : SSL_R_VERSION_TOO_LOW;
2316
0
}
2317
2318
/*
2319
 * ssl_choose_client_version - Choose client (D)TLS version.  Called when the
2320
 * server HELLO is received to select the final client protocol version and
2321
 * the version specific method.
2322
 *
2323
 * @s: client SSL handle.
2324
 * @version: The proposed version from the server's HELLO.
2325
 * @extensions: The extensions received
2326
 *
2327
 * Returns 1 on success or 0 on error.
2328
 */
2329
int ssl_choose_client_version(SSL_CONNECTION *s, int version,
2330
    RAW_EXTENSION *extensions)
2331
0
{
2332
0
    const version_info *vent;
2333
0
    const version_info *table;
2334
0
    int ret, ver_min, ver_max, real_max, origv;
2335
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2336
2337
0
    origv = s->version;
2338
0
    s->version = version;
2339
2340
    /* This will overwrite s->version if the extension is present */
2341
0
    if (!tls_parse_extension(s, TLSEXT_IDX_supported_versions,
2342
0
            SSL_EXT_TLS1_2_SERVER_HELLO
2343
0
                | SSL_EXT_TLS1_3_SERVER_HELLO,
2344
0
            extensions,
2345
0
            NULL, 0)) {
2346
0
        s->version = origv;
2347
0
        return 0;
2348
0
    }
2349
2350
0
    if (s->hello_retry_request != SSL_HRR_NONE
2351
0
        && s->version != TLS1_3_VERSION) {
2352
0
        s->version = origv;
2353
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2354
0
        return 0;
2355
0
    }
2356
2357
0
    switch (ssl->method->version) {
2358
0
    default:
2359
0
        if (s->version != ssl->method->version) {
2360
0
            s->version = origv;
2361
0
            SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_WRONG_SSL_VERSION);
2362
0
            return 0;
2363
0
        }
2364
        /*
2365
         * If this SSL handle is not from a version flexible method we don't
2366
         * (and never did) check min/max, FIPS or Suite B constraints.  Hope
2367
         * that's OK.  It is up to the caller to not choose fixed protocol
2368
         * versions they don't want.  If not, then easy to fix, just return
2369
         * ssl_method_error(s, s->method)
2370
         */
2371
0
        if (!ssl_set_record_protocol_version(s, s->version)) {
2372
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2373
0
            return 0;
2374
0
        }
2375
0
        return 1;
2376
0
    case TLS_ANY_VERSION:
2377
0
        table = tls_version_table;
2378
0
        break;
2379
0
    case DTLS_ANY_VERSION:
2380
0
        table = dtls_version_table;
2381
0
        break;
2382
0
    }
2383
2384
0
    ret = ssl_get_min_max_version(s, &ver_min, &ver_max, &real_max);
2385
0
    if (ret != 0) {
2386
0
        s->version = origv;
2387
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, ret);
2388
0
        return 0;
2389
0
    }
2390
0
    if (ssl_version_cmp(s, s->version, ver_min) < 0
2391
0
        || ssl_version_cmp(s, s->version, ver_max) > 0) {
2392
0
        s->version = origv;
2393
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2394
0
        return 0;
2395
0
    }
2396
2397
0
    if ((s->mode & SSL_MODE_SEND_FALLBACK_SCSV) == 0)
2398
0
        real_max = ver_max;
2399
2400
    /* Check for downgrades */
2401
    /* TODO(DTLSv1.3): Update this code for DTLSv1.3 */
2402
0
    if (!SSL_CONNECTION_IS_DTLS(s) && real_max > s->version) {
2403
        /* Signal applies to all versions */
2404
0
        if (memcmp(tls11downgrade,
2405
0
                s->s3.server_random + SSL3_RANDOM_SIZE
2406
0
                    - sizeof(tls11downgrade),
2407
0
                sizeof(tls11downgrade))
2408
0
            == 0) {
2409
0
            s->version = origv;
2410
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2411
0
                SSL_R_INAPPROPRIATE_FALLBACK);
2412
0
            return 0;
2413
0
        }
2414
        /* Only when accepting TLS1.3 */
2415
0
        if (real_max == TLS1_3_VERSION
2416
0
            && memcmp(tls12downgrade,
2417
0
                   s->s3.server_random + SSL3_RANDOM_SIZE
2418
0
                       - sizeof(tls12downgrade),
2419
0
                   sizeof(tls12downgrade))
2420
0
                == 0) {
2421
0
            s->version = origv;
2422
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2423
0
                SSL_R_INAPPROPRIATE_FALLBACK);
2424
0
            return 0;
2425
0
        }
2426
0
    }
2427
2428
0
    for (vent = table; vent->version != 0; ++vent) {
2429
0
        if (vent->cmeth == NULL || s->version != vent->version)
2430
0
            continue;
2431
2432
0
        ssl->method = vent->cmeth();
2433
0
        if (!ssl_set_record_protocol_version(s, s->version)) {
2434
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2435
0
            return 0;
2436
0
        }
2437
0
        return 1;
2438
0
    }
2439
2440
0
    s->version = origv;
2441
0
    SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNSUPPORTED_PROTOCOL);
2442
0
    return 0;
2443
0
}
2444
2445
/*
2446
 * ssl_get_min_max_version - get minimum and maximum protocol version
2447
 * @s: The SSL connection
2448
 * @min_version: The minimum supported version
2449
 * @max_version: The maximum supported version
2450
 * @real_max:    The highest version below the lowest compile time version hole
2451
 *               where that hole lies above at least one run-time enabled
2452
 *               protocol.
2453
 *
2454
 * Work out what version we should be using for the initial ClientHello if the
2455
 * version is initially (D)TLS_ANY_VERSION.  We apply any explicit SSL_OP_NO_xxx
2456
 * options, the MinProtocol and MaxProtocol configuration commands, any Suite B
2457
 * constraints and any floor imposed by the security level here,
2458
 * so we don't advertise the wrong protocol version to only reject the outcome later.
2459
 *
2460
 * Computing the right floor matters.  If, e.g., TLS 1.0 and 1.2 are enabled,
2461
 * TLS 1.1 is disabled, but the security level, Suite-B  and/or MinProtocol
2462
 * only allow TLS 1.2, we want to advertise TLS1.2, *not* TLS1.
2463
 *
2464
 * Returns 0 on success or an SSL error reason number on failure.  On failure
2465
 * min_version and max_version will also be set to 0.
2466
 */
2467
int ssl_get_min_max_version(const SSL_CONNECTION *s, int *min_version,
2468
    int *max_version, int *real_max)
2469
0
{
2470
0
    int version, tmp_real_max;
2471
0
    int hole;
2472
0
    const SSL_METHOD *method;
2473
0
    const version_info *table;
2474
0
    const version_info *vent;
2475
0
    const SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2476
2477
0
    switch (ssl->method->version) {
2478
0
    default:
2479
        /*
2480
         * If this SSL handle is not from a version flexible method we don't
2481
         * (and never did) check min/max FIPS or Suite B constraints.  Hope
2482
         * that's OK.  It is up to the caller to not choose fixed protocol
2483
         * versions they don't want.  If not, then easy to fix, just return
2484
         * ssl_method_error(s, s->method)
2485
         */
2486
0
        *min_version = *max_version = s->version;
2487
        /*
2488
         * Providing a real_max only makes sense where we're using a version
2489
         * flexible method.
2490
         */
2491
0
        if (!ossl_assert(real_max == NULL))
2492
0
            return ERR_R_INTERNAL_ERROR;
2493
0
        return 0;
2494
0
    case TLS_ANY_VERSION:
2495
0
        table = tls_version_table;
2496
0
        break;
2497
0
    case DTLS_ANY_VERSION:
2498
0
        table = dtls_version_table;
2499
0
        break;
2500
0
    }
2501
2502
    /*
2503
     * SSL_OP_NO_X disables all protocols above X *if* there are some protocols
2504
     * below X enabled. This is required in order to maintain the "version
2505
     * capability" vector contiguous. Any versions with a NULL client method
2506
     * (protocol version client is disabled at compile-time) is also a "hole".
2507
     *
2508
     * Our initial state is hole == 1, version == 0.  That is, versions above
2509
     * the first version in the method table are disabled (a "hole" above
2510
     * the valid protocol entries) and we don't have a selected version yet.
2511
     *
2512
     * Whenever "hole == 1", and we hit an enabled method, its version becomes
2513
     * the selected version.  We're no longer in a hole, so "hole" becomes 0.
2514
     *
2515
     * If "hole == 0" and we hit an enabled method, we support a contiguous
2516
     * range of at least two methods.  If we hit a disabled method,
2517
     * then hole becomes true again, but nothing else changes yet,
2518
     * because all the remaining methods may be disabled too.
2519
     * If we again hit an enabled method after the new hole, it becomes
2520
     * selected, as we start from scratch.
2521
     */
2522
0
    *min_version = version = 0;
2523
0
    hole = 1;
2524
0
    if (real_max != NULL)
2525
0
        *real_max = 0;
2526
0
    tmp_real_max = 0;
2527
0
    for (vent = table; vent->version != 0; ++vent) {
2528
        /*
2529
         * A table entry with a NULL client method is still a hole in the
2530
         * "version capability" vector.
2531
         */
2532
0
        if (vent->cmeth == NULL) {
2533
0
            hole = 1;
2534
0
            tmp_real_max = 0;
2535
0
            continue;
2536
0
        }
2537
0
        method = vent->cmeth();
2538
2539
0
        if (hole == 1 && tmp_real_max == 0)
2540
0
            tmp_real_max = vent->version;
2541
2542
0
        if (ssl_method_error(s, method) != 0) {
2543
0
            hole = 1;
2544
0
        } else if (!hole) {
2545
0
            *min_version = method->version;
2546
0
        } else {
2547
0
            if (real_max != NULL && tmp_real_max != 0)
2548
0
                *real_max = tmp_real_max;
2549
0
            version = method->version;
2550
0
            *min_version = version;
2551
0
            hole = 0;
2552
0
        }
2553
0
    }
2554
2555
0
    *max_version = version;
2556
2557
    /* Fail if everything is disabled */
2558
0
    if (version == 0)
2559
0
        return SSL_R_NO_PROTOCOLS_AVAILABLE;
2560
2561
0
    return 0;
2562
0
}
2563
2564
/*
2565
 * ssl_set_client_hello_version - Work out what version we should be using for
2566
 * the initial ClientHello.legacy_version field.
2567
 *
2568
 * @s: client SSL handle.
2569
 *
2570
 * Returns 0 on success or an SSL error reason number on failure.
2571
 */
2572
int ssl_set_client_hello_version(SSL_CONNECTION *s)
2573
0
{
2574
0
    int ver_min, ver_max, ret;
2575
2576
    /*
2577
     * In a renegotiation we always send the same client_version that we sent
2578
     * last time, regardless of which version we eventually negotiated.
2579
     */
2580
0
    if (!SSL_IS_FIRST_HANDSHAKE(s))
2581
0
        return 0;
2582
2583
0
    ret = ssl_get_min_max_version(s, &ver_min, &ver_max, NULL);
2584
2585
0
    if (ret != 0)
2586
0
        return ret;
2587
2588
0
    s->version = ver_max;
2589
2590
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
2591
0
        if (ver_max == DTLS1_BAD_VER) {
2592
            /*
2593
             * Even though this is technically before version negotiation,
2594
             * because we have asked for DTLS1_BAD_VER we will never negotiate
2595
             * anything else, and this has impacts on the record layer for when
2596
             * we read the ServerHello. So we need to tell the record layer
2597
             * about this immediately.
2598
             */
2599
0
            if (!ssl_set_record_protocol_version(s, ver_max))
2600
0
                return 0;
2601
0
        }
2602
0
    } else if (ver_max > TLS1_2_VERSION) {
2603
        /* TLS1.3 always uses TLS1.2 in the legacy_version field */
2604
0
        ver_max = TLS1_2_VERSION;
2605
0
    }
2606
2607
0
    s->client_version = ver_max;
2608
0
    return 0;
2609
0
}
2610
2611
/*
2612
 * Checks a list of |groups| to determine if the |group_id| is in it. If it is
2613
 * and |checkallow| is 1 then additionally check if the group is allowed to be
2614
 * used. Returns 1 if the group is in the list (and allowed if |checkallow| is
2615
 * 1) or 0 otherwise. If provided a pointer it will also return the position
2616
 * where the group was found.
2617
 */
2618
int check_in_list(SSL_CONNECTION *s, uint16_t group_id, const uint16_t *groups,
2619
    size_t num_groups, int checkallow, size_t *pos)
2620
0
{
2621
0
    size_t i;
2622
2623
0
    if (groups == NULL || num_groups == 0)
2624
0
        return 0;
2625
2626
0
    for (i = 0; i < num_groups; i++) {
2627
0
        uint16_t group = groups[i];
2628
2629
0
        if (group_id == group
2630
0
            && (!checkallow
2631
0
                || tls_group_allowed(s, group, SSL_SECOP_CURVE_CHECK))) {
2632
0
            if (pos != NULL)
2633
0
                *pos = i;
2634
0
            return 1;
2635
0
        }
2636
0
    }
2637
2638
0
    return 0;
2639
0
}
2640
2641
/* Replace ClientHello1 in the transcript hash with a synthetic message */
2642
int create_synthetic_message_hash(SSL_CONNECTION *s,
2643
    const unsigned char *hashval,
2644
    size_t hashlen, const unsigned char *hrr,
2645
    size_t hrrlen)
2646
0
{
2647
0
    unsigned char hashvaltmp[EVP_MAX_MD_SIZE];
2648
0
    unsigned char msghdr[SSL3_HM_HEADER_LENGTH];
2649
2650
0
    memset(msghdr, 0, sizeof(msghdr));
2651
2652
0
    if (hashval == NULL) {
2653
0
        hashval = hashvaltmp;
2654
0
        hashlen = 0;
2655
        /* Get the hash of the initial ClientHello */
2656
0
        if (!ssl3_digest_cached_records(s, 0)
2657
0
            || !ssl_handshake_hash(s, hashvaltmp, sizeof(hashvaltmp),
2658
0
                &hashlen)) {
2659
            /* SSLfatal() already called */
2660
0
            return 0;
2661
0
        }
2662
0
    }
2663
2664
    /* Reinitialise the transcript hash */
2665
0
    if (!ssl3_init_finished_mac(s)) {
2666
        /* SSLfatal() already called */
2667
0
        return 0;
2668
0
    }
2669
2670
    /* Inject the synthetic message_hash message */
2671
0
    msghdr[0] = SSL3_MT_MESSAGE_HASH;
2672
0
    msghdr[SSL3_HM_HEADER_LENGTH - 1] = (unsigned char)hashlen;
2673
0
    if (!ssl3_finish_mac(s, msghdr, SSL3_HM_HEADER_LENGTH)
2674
0
        || !ssl3_finish_mac(s, hashval, hashlen)) {
2675
        /* SSLfatal() already called */
2676
0
        return 0;
2677
0
    }
2678
2679
    /*
2680
     * Now re-inject the HRR and current message if appropriate (we just deleted
2681
     * it when we reinitialised the transcript hash above). Only necessary after
2682
     * receiving a ClientHello2 with a cookie.
2683
     */
2684
0
    if (hrr != NULL
2685
0
        && (!ssl3_finish_mac(s, hrr, hrrlen)
2686
0
            || !ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
2687
0
                s->s3.tmp.message_size
2688
0
                    + SSL3_HM_HEADER_LENGTH))) {
2689
        /* SSLfatal() already called */
2690
0
        return 0;
2691
0
    }
2692
2693
0
    return 1;
2694
0
}
2695
2696
static int ca_dn_cmp(const X509_NAME *const *a, const X509_NAME *const *b)
2697
0
{
2698
0
    return X509_NAME_cmp(*a, *b);
2699
0
}
2700
2701
int parse_ca_names(SSL_CONNECTION *s, PACKET *pkt)
2702
0
{
2703
0
    STACK_OF(X509_NAME) *ca_sk = sk_X509_NAME_new(ca_dn_cmp);
2704
0
    X509_NAME *xn = NULL;
2705
0
    PACKET cadns;
2706
2707
0
    if (ca_sk == NULL) {
2708
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2709
0
        goto err;
2710
0
    }
2711
    /* get the CA RDNs */
2712
0
    if (!PACKET_get_length_prefixed_2(pkt, &cadns)) {
2713
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2714
0
        goto err;
2715
0
    }
2716
2717
0
    while (PACKET_remaining(&cadns)) {
2718
0
        const unsigned char *namestart, *namebytes;
2719
0
        unsigned int name_len;
2720
2721
0
        if (!PACKET_get_net_2(&cadns, &name_len)
2722
0
            || !PACKET_get_bytes(&cadns, &namebytes, name_len)) {
2723
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2724
0
            goto err;
2725
0
        }
2726
2727
0
        namestart = namebytes;
2728
0
        if ((xn = d2i_X509_NAME(NULL, &namebytes, name_len)) == NULL) {
2729
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2730
0
            goto err;
2731
0
        }
2732
0
        if (namebytes != (namestart + name_len)) {
2733
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CA_DN_LENGTH_MISMATCH);
2734
0
            goto err;
2735
0
        }
2736
2737
0
        if (!sk_X509_NAME_push(ca_sk, xn)) {
2738
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2739
0
            goto err;
2740
0
        }
2741
0
        xn = NULL;
2742
0
    }
2743
2744
0
    sk_X509_NAME_pop_free(s->s3.tmp.peer_ca_names, X509_NAME_free);
2745
0
    s->s3.tmp.peer_ca_names = ca_sk;
2746
2747
0
    return 1;
2748
2749
0
err:
2750
0
    sk_X509_NAME_pop_free(ca_sk, X509_NAME_free);
2751
0
    X509_NAME_free(xn);
2752
0
    return 0;
2753
0
}
2754
2755
const STACK_OF(X509_NAME) *get_ca_names(SSL_CONNECTION *s)
2756
0
{
2757
0
    const STACK_OF(X509_NAME) *ca_sk = NULL;
2758
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2759
2760
0
    if (s->server) {
2761
0
        ca_sk = SSL_get_client_CA_list(ssl);
2762
0
        if (ca_sk != NULL && sk_X509_NAME_num(ca_sk) == 0)
2763
0
            ca_sk = NULL;
2764
0
    }
2765
2766
0
    if (ca_sk == NULL)
2767
0
        ca_sk = SSL_get0_CA_list(ssl);
2768
2769
0
    return ca_sk;
2770
0
}
2771
2772
int construct_ca_names(SSL_CONNECTION *s, const STACK_OF(X509_NAME) *ca_sk,
2773
    WPACKET *pkt)
2774
0
{
2775
    /* Start sub-packet for client CA list */
2776
0
    if (!WPACKET_start_sub_packet_u16(pkt)) {
2777
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2778
0
        return 0;
2779
0
    }
2780
2781
0
    if ((ca_sk != NULL) && !(s->options & SSL_OP_DISABLE_TLSEXT_CA_NAMES)) {
2782
0
        int i;
2783
2784
0
        for (i = 0; i < sk_X509_NAME_num(ca_sk); i++) {
2785
0
            unsigned char *namebytes;
2786
0
            X509_NAME *name = sk_X509_NAME_value(ca_sk, i);
2787
0
            int namelen;
2788
2789
0
            if (name == NULL
2790
0
                || (namelen = i2d_X509_NAME(name, NULL)) < 0
2791
0
                || !WPACKET_sub_allocate_bytes_u16(pkt, namelen,
2792
0
                    &namebytes)
2793
0
                || i2d_X509_NAME(name, &namebytes) != namelen) {
2794
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2795
0
                return 0;
2796
0
            }
2797
0
        }
2798
0
    }
2799
2800
0
    if (!WPACKET_close(pkt)) {
2801
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2802
0
        return 0;
2803
0
    }
2804
2805
0
    return 1;
2806
0
}
2807
2808
/* Create a buffer containing data to be signed for server key exchange */
2809
size_t construct_key_exchange_tbs(SSL_CONNECTION *s, unsigned char **ptbs,
2810
    const void *param, size_t paramlen)
2811
0
{
2812
0
    size_t tbslen = 2 * SSL3_RANDOM_SIZE + paramlen;
2813
0
    unsigned char *tbs = OPENSSL_malloc(tbslen);
2814
2815
0
    if (tbs == NULL) {
2816
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2817
0
        return 0;
2818
0
    }
2819
0
    memcpy(tbs, s->s3.client_random, SSL3_RANDOM_SIZE);
2820
0
    memcpy(tbs + SSL3_RANDOM_SIZE, s->s3.server_random, SSL3_RANDOM_SIZE);
2821
2822
0
    memcpy(tbs + SSL3_RANDOM_SIZE * 2, param, paramlen);
2823
2824
0
    *ptbs = tbs;
2825
0
    return tbslen;
2826
0
}
2827
2828
/*
2829
 * Saves the current handshake digest for Post-Handshake Auth,
2830
 * Done after ClientFinished is processed, done exactly once
2831
 */
2832
int tls13_save_handshake_digest_for_pha(SSL_CONNECTION *s)
2833
0
{
2834
0
    if (s->pha_dgst == NULL) {
2835
0
        if (!ssl3_digest_cached_records(s, 1))
2836
            /* SSLfatal() already called */
2837
0
            return 0;
2838
2839
0
        s->pha_dgst = EVP_MD_CTX_new();
2840
0
        if (s->pha_dgst == NULL) {
2841
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2842
0
            return 0;
2843
0
        }
2844
0
        if (!EVP_MD_CTX_copy_ex(s->pha_dgst,
2845
0
                s->s3.handshake_dgst)) {
2846
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2847
0
            EVP_MD_CTX_free(s->pha_dgst);
2848
0
            s->pha_dgst = NULL;
2849
0
            return 0;
2850
0
        }
2851
0
    }
2852
0
    return 1;
2853
0
}
2854
2855
/*
2856
 * Restores the Post-Handshake Auth handshake digest
2857
 * Done just before sending/processing the Cert Request
2858
 */
2859
int tls13_restore_handshake_digest_for_pha(SSL_CONNECTION *s)
2860
0
{
2861
0
    if (s->pha_dgst == NULL) {
2862
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2863
0
        return 0;
2864
0
    }
2865
0
    if (!EVP_MD_CTX_copy_ex(s->s3.handshake_dgst,
2866
0
            s->pha_dgst)) {
2867
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2868
0
        return 0;
2869
0
    }
2870
0
    return 1;
2871
0
}
2872
2873
#ifndef OPENSSL_NO_COMP_ALG
2874
MSG_PROCESS_RETURN tls13_process_compressed_certificate(SSL_CONNECTION *sc,
2875
    PACKET *pkt,
2876
    PACKET *tmppkt,
2877
    BUF_MEM *buf)
2878
{
2879
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2880
    int comp_alg;
2881
    COMP_METHOD *method = NULL;
2882
    COMP_CTX *comp = NULL;
2883
    size_t expected_length;
2884
    size_t comp_length;
2885
    int i;
2886
    int found = 0;
2887
2888
    if (buf == NULL) {
2889
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2890
        goto err;
2891
    }
2892
    if (!PACKET_get_net_2(pkt, (unsigned int *)&comp_alg)) {
2893
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, ERR_R_INTERNAL_ERROR);
2894
        goto err;
2895
    }
2896
    /* If we have a prefs list, make sure the algorithm is in it */
2897
    if (sc->cert_comp_prefs[0] != TLSEXT_comp_cert_none) {
2898
        for (i = 0; sc->cert_comp_prefs[i] != TLSEXT_comp_cert_none; i++) {
2899
            if (sc->cert_comp_prefs[i] == comp_alg) {
2900
                found = 1;
2901
                break;
2902
            }
2903
        }
2904
        if (!found) {
2905
            SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_COMPRESSION_ALGORITHM);
2906
            goto err;
2907
        }
2908
    }
2909
    if (!ossl_comp_has_alg(comp_alg)) {
2910
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2911
        goto err;
2912
    }
2913
    switch (comp_alg) {
2914
    case TLSEXT_comp_cert_zlib:
2915
        method = COMP_zlib_oneshot();
2916
        break;
2917
    case TLSEXT_comp_cert_brotli:
2918
        method = COMP_brotli_oneshot();
2919
        break;
2920
    case TLSEXT_comp_cert_zstd:
2921
        method = COMP_zstd_oneshot();
2922
        break;
2923
    default:
2924
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_COMPRESSION_ALGORITHM);
2925
        goto err;
2926
    }
2927
2928
    if ((comp = COMP_CTX_new(method)) == NULL
2929
        || !PACKET_get_net_3_len(pkt, &expected_length)
2930
        || !PACKET_get_net_3_len(pkt, &comp_length)) {
2931
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2932
        goto err;
2933
    }
2934
2935
    /* Prevent excessive pre-decompression allocation */
2936
    if (expected_length > sc->max_cert_list) {
2937
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_EXCESSIVE_MESSAGE_SIZE);
2938
        goto err;
2939
    }
2940
2941
    if (PACKET_remaining(pkt) != comp_length || comp_length == 0) {
2942
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_DECOMPRESSION);
2943
        goto err;
2944
    }
2945
2946
    if (!BUF_MEM_grow(buf, expected_length)
2947
        || !PACKET_buf_init(tmppkt, (unsigned char *)buf->data, expected_length)
2948
        || COMP_expand_block(comp, (unsigned char *)buf->data, (int)expected_length,
2949
               (unsigned char *)PACKET_data(pkt),
2950
               (int)comp_length)
2951
            != (int)expected_length) {
2952
        SSLfatal(sc, SSL_AD_BAD_CERTIFICATE, SSL_R_BAD_DECOMPRESSION);
2953
        goto err;
2954
    }
2955
    ret = MSG_PROCESS_CONTINUE_PROCESSING;
2956
err:
2957
    COMP_CTX_free(comp);
2958
    return ret;
2959
}
2960
#endif