Coverage Report

Created: 2023-09-25 06:43

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