Coverage Report

Created: 2023-09-25 06:41

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