Coverage Report

Created: 2026-09-12 06:55

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl40/ssl/statem/statem_srvr.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4
 * Copyright 2005 Nokia. All rights reserved.
5
 *
6
 * Licensed under the Apache License 2.0 (the "License").  You may not use
7
 * this file except in compliance with the License.  You can obtain a copy
8
 * in the file LICENSE in the source distribution or at
9
 * https://www.openssl.org/source/license.html
10
 */
11
12
#include "internal/e_os.h"
13
14
#include <stdio.h>
15
#include "../ssl_local.h"
16
#include "statem_local.h"
17
#include "internal/constant_time.h"
18
#include "internal/cryptlib.h"
19
#include "internal/ssl_unwrap.h"
20
#include "internal/sizes.h"
21
#include <openssl/buffer.h>
22
#include <openssl/rand.h>
23
#include <openssl/objects.h>
24
#include <openssl/evp.h>
25
#include <openssl/x509.h>
26
#include <openssl/dh.h>
27
#include <openssl/rsa.h>
28
#include <openssl/bn.h>
29
#include <openssl/md5.h>
30
#include <openssl/trace.h>
31
#include <openssl/core_names.h>
32
#include <openssl/asn1t.h>
33
#include <openssl/comp.h>
34
#include "internal/comp.h"
35
#include <openssl/ocsp.h>
36
37
0
#define TICKET_NONCE_SIZE 8
38
39
#ifndef OPENSSL_NO_ECH
40
#include "../ech/ech_local.h"
41
#endif
42
43
typedef struct {
44
    ASN1_TYPE *kxBlob;
45
    ASN1_TYPE *opaqueBlob;
46
} GOST_KX_MESSAGE;
47
48
DECLARE_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
49
50
ASN1_SEQUENCE(GOST_KX_MESSAGE) = {
51
    ASN1_SIMPLE(GOST_KX_MESSAGE, kxBlob, ASN1_ANY),
52
    ASN1_OPT(GOST_KX_MESSAGE, opaqueBlob, ASN1_ANY),
53
0
} ASN1_SEQUENCE_END(GOST_KX_MESSAGE)
54
0
55
0
IMPLEMENT_ASN1_FUNCTIONS(GOST_KX_MESSAGE)
56
0
57
0
static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,
58
0
    WPACKET *pkt);
59
0
60
0
static ossl_inline int received_client_cert(const SSL_CONNECTION *sc)
61
22.4k
{
62
22.4k
    return sc->session->peer_rpk != NULL || sc->session->peer != NULL;
63
22.4k
}
64
65
/*
66
 * ossl_statem_server13_read_transition() encapsulates the logic for the allowed
67
 * handshake state transitions when a TLSv1.3 server is reading messages from
68
 * the client. The message type that the client has sent is provided in |mt|.
69
 * The current state is in |s->statem.hand_state|.
70
 *
71
 * Return values are 1 for success (transition allowed) and  0 on error
72
 * (transition not allowed)
73
 */
74
static int ossl_statem_server13_read_transition(SSL_CONNECTION *s, int mt)
75
198
{
76
198
    OSSL_STATEM *st = &s->statem;
77
78
    /*
79
     * Note: There is no case for TLS_ST_BEFORE because at that stage we have
80
     * not negotiated TLSv1.3 yet, so that case is handled by
81
     * ossl_statem_server_read_transition()
82
     */
83
198
    switch (st->hand_state) {
84
0
    default:
85
0
        break;
86
87
198
    case TLS_ST_EARLY_DATA:
88
198
        if (s->hello_retry_request == SSL_HRR_PENDING) {
89
195
            if (mt == SSL3_MT_CLIENT_HELLO) {
90
191
                st->hand_state = TLS_ST_SR_CLNT_HELLO;
91
191
                return 1;
92
191
            }
93
4
            break;
94
195
        } else if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED
95
0
            && !SSL_NO_EOED(s)) {
96
0
            if (mt == SSL3_MT_END_OF_EARLY_DATA) {
97
0
                st->hand_state = TLS_ST_SR_END_OF_EARLY_DATA;
98
0
                return 1;
99
0
            }
100
0
            break;
101
0
        }
102
        /* Fall through */
103
104
3
    case TLS_ST_SR_END_OF_EARLY_DATA:
105
3
    case TLS_ST_SW_FINISHED:
106
3
        if (s->s3.tmp.cert_request) {
107
0
            if (mt == SSL3_MT_CERTIFICATE) {
108
0
                st->hand_state = TLS_ST_SR_CERT;
109
0
                return 1;
110
0
            }
111
#ifndef OPENSSL_NO_COMP_ALG
112
            if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
113
                && s->ext.compress_certificate_sent) {
114
                st->hand_state = TLS_ST_SR_COMP_CERT;
115
                return 1;
116
            }
117
#endif
118
3
        } else {
119
3
            if (mt == SSL3_MT_FINISHED) {
120
0
                st->hand_state = TLS_ST_SR_FINISHED;
121
0
                return 1;
122
0
            }
123
3
        }
124
3
        break;
125
126
3
    case TLS_ST_SR_COMP_CERT:
127
0
    case TLS_ST_SR_CERT:
128
0
        if (!received_client_cert(s)) {
129
0
            if (mt == SSL3_MT_FINISHED) {
130
0
                st->hand_state = TLS_ST_SR_FINISHED;
131
0
                return 1;
132
0
            }
133
0
        } else {
134
0
            if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
135
0
                st->hand_state = TLS_ST_SR_CERT_VRFY;
136
0
                return 1;
137
0
            }
138
0
        }
139
0
        break;
140
141
0
    case TLS_ST_SR_CERT_VRFY:
142
0
        if (mt == SSL3_MT_FINISHED) {
143
0
            st->hand_state = TLS_ST_SR_FINISHED;
144
0
            return 1;
145
0
        }
146
0
        break;
147
148
0
    case TLS_ST_OK:
149
        /*
150
         * Its never ok to start processing handshake messages in the middle of
151
         * early data (i.e. before we've received the end of early data alert)
152
         */
153
0
        if (s->early_data_state == SSL_EARLY_DATA_READING)
154
0
            break;
155
156
0
        if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
157
0
            if (mt == SSL3_MT_CERTIFICATE) {
158
0
                st->hand_state = TLS_ST_SR_CERT;
159
0
                return 1;
160
0
            }
161
#ifndef OPENSSL_NO_COMP_ALG
162
            if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
163
                && s->ext.compress_certificate_sent) {
164
                st->hand_state = TLS_ST_SR_COMP_CERT;
165
                return 1;
166
            }
167
#endif
168
0
        }
169
170
0
        if (mt == SSL3_MT_KEY_UPDATE && !SSL_IS_QUIC_HANDSHAKE(s)) {
171
0
            st->hand_state = TLS_ST_SR_KEY_UPDATE;
172
0
            return 1;
173
0
        }
174
0
        break;
175
198
    }
176
177
    /* No valid transition found */
178
7
    return 0;
179
198
}
180
181
/*
182
 * ossl_statem_server_read_transition() encapsulates the logic for the allowed
183
 * handshake state transitions when the server is reading messages from the
184
 * client. The message type that the client has sent is provided in |mt|. The
185
 * current state is in |s->statem.hand_state|.
186
 *
187
 * Return values are 1 for success (transition allowed) and  0 on error
188
 * (transition not allowed)
189
 */
190
int ossl_statem_server_read_transition(SSL_CONNECTION *s, int mt)
191
7.43k
{
192
7.43k
    OSSL_STATEM *st = &s->statem;
193
194
7.43k
    if (SSL_CONNECTION_IS_TLS13(s)) {
195
60
        if (!ossl_statem_server13_read_transition(s, mt))
196
2
            goto err;
197
58
        return 1;
198
60
    }
199
200
7.37k
    switch (st->hand_state) {
201
0
    default:
202
0
        break;
203
204
5.39k
    case TLS_ST_BEFORE:
205
5.46k
    case TLS_ST_OK:
206
5.46k
    case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
207
5.46k
        if (mt == SSL3_MT_CLIENT_HELLO) {
208
5.38k
            st->hand_state = TLS_ST_SR_CLNT_HELLO;
209
5.38k
            return 1;
210
5.38k
        }
211
79
        break;
212
213
1.34k
    case TLS_ST_SW_SRVR_DONE:
214
        /*
215
         * If we get a CKE message after a ServerDone then either
216
         * 1) We didn't request a Certificate
217
         * OR
218
         * 2) We did request one and we allow no Certificate to be returned
219
         */
220
1.34k
        if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
221
1.30k
            if (!s->s3.tmp.cert_request) {
222
1.30k
                st->hand_state = TLS_ST_SR_KEY_EXCH;
223
1.30k
                return 1;
224
1.30k
            }
225
1.30k
        } else if (s->s3.tmp.cert_request) {
226
0
            if (mt == SSL3_MT_CERTIFICATE) {
227
0
                st->hand_state = TLS_ST_SR_CERT;
228
0
                return 1;
229
0
            }
230
0
        }
231
37
        break;
232
233
37
    case TLS_ST_SR_CERT:
234
0
        if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
235
0
            st->hand_state = TLS_ST_SR_KEY_EXCH;
236
0
            return 1;
237
0
        }
238
0
        break;
239
240
439
    case TLS_ST_SR_KEY_EXCH:
241
        /*
242
         * We should only process a CertificateVerify message if we have
243
         * received a Certificate from the client. If so then |s->session->peer|
244
         * will be non NULL. In some instances a CertificateVerify message is
245
         * not required even if the peer has sent a Certificate (e.g. such as in
246
         * the case of static DH). In that case |st->no_cert_verify| should be
247
         * set.
248
         */
249
439
        if (!received_client_cert(s) || st->no_cert_verify) {
250
439
            if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
251
                /*
252
                 * For the ECDH ciphersuites when the client sends its ECDH
253
                 * pub key in a certificate, the CertificateVerify message is
254
                 * not sent. Also for GOST ciphersuites when the client uses
255
                 * its key from the certificate for key exchange.
256
                 */
257
386
                st->hand_state = TLS_ST_SR_CHANGE;
258
386
                return 1;
259
386
            }
260
439
        } else {
261
0
            if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
262
0
                st->hand_state = TLS_ST_SR_CERT_VRFY;
263
0
                return 1;
264
0
            }
265
0
        }
266
53
        break;
267
268
53
    case TLS_ST_SR_CERT_VRFY:
269
0
        if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
270
0
            st->hand_state = TLS_ST_SR_CHANGE;
271
0
            return 1;
272
0
        }
273
0
        break;
274
275
109
    case TLS_ST_SR_CHANGE:
276
109
#ifndef OPENSSL_NO_NEXTPROTONEG
277
109
        if (s->s3.npn_seen) {
278
0
            if (mt == SSL3_MT_NEXT_PROTO) {
279
0
                st->hand_state = TLS_ST_SR_NEXT_PROTO;
280
0
                return 1;
281
0
            }
282
109
        } else {
283
109
#endif
284
109
            if (mt == SSL3_MT_FINISHED) {
285
32
                st->hand_state = TLS_ST_SR_FINISHED;
286
32
                return 1;
287
32
            }
288
109
#ifndef OPENSSL_NO_NEXTPROTONEG
289
109
        }
290
77
#endif
291
77
        break;
292
293
77
#ifndef OPENSSL_NO_NEXTPROTONEG
294
77
    case TLS_ST_SR_NEXT_PROTO:
295
0
        if (mt == SSL3_MT_FINISHED) {
296
0
            st->hand_state = TLS_ST_SR_FINISHED;
297
0
            return 1;
298
0
        }
299
0
        break;
300
0
#endif
301
302
21
    case TLS_ST_SW_FINISHED:
303
21
        if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
304
16
            st->hand_state = TLS_ST_SR_CHANGE;
305
16
            return 1;
306
16
        }
307
5
        break;
308
7.37k
    }
309
310
253
err:
311
    /* No valid transition found */
312
253
    if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
313
3
        BIO *rbio;
314
315
        /*
316
         * CCS messages don't have a message sequence number so this is probably
317
         * because of an out-of-order CCS. We'll just drop it.
318
         */
319
3
        s->init_num = 0;
320
3
        s->rwstate = SSL_READING;
321
3
        rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));
322
3
        BIO_clear_retry_flags(rbio);
323
3
        BIO_set_retry_read(rbio);
324
3
        return 0;
325
3
    }
326
253
    SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
327
250
    return 0;
328
253
}
329
330
/*
331
 * Should we send a ServerKeyExchange message?
332
 *
333
 * Valid return values are:
334
 *   1: Yes
335
 *   0: No
336
 */
337
static int send_server_key_exchange(SSL_CONNECTION *s)
338
20.3k
{
339
20.3k
    unsigned long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
340
341
    /*
342
     * only send a ServerKeyExchange if DH or fortezza but we have a
343
     * sign only certificate PSK: may send PSK identity hints For
344
     * ECC ciphersuites, we send a serverKeyExchange message only if
345
     * the cipher suite is either ECDH-anon or ECDHE. In other cases,
346
     * the server certificate contains the server's public key for
347
     * key exchange.
348
     */
349
20.3k
    if (alg_k & (SSL_kDHE | SSL_kECDHE)
350
    /*
351
     * PSK: send ServerKeyExchange if PSK identity hint if
352
     * provided
353
     */
354
10.0k
#ifndef OPENSSL_NO_PSK
355
        /* Only send SKE if we have identity hint for plain PSK */
356
10.0k
        || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
357
0
            && s->cert->psk_identity_hint)
358
        /* For other PSK always send SKE */
359
10.0k
        || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
360
10.0k
#endif
361
10.0k
#ifndef OPENSSL_NO_SRP
362
        /* SRP: send ServerKeyExchange */
363
10.0k
        || (alg_k & SSL_kSRP)
364
20.3k
#endif
365
20.3k
    ) {
366
10.2k
        return 1;
367
10.2k
    }
368
369
10.0k
    return 0;
370
20.3k
}
371
372
/*
373
 * Used to determine if we should send a CompressedCertificate message
374
 *
375
 * Returns the algorithm to use, TLSEXT_comp_cert_none means no compression
376
 */
377
static int get_compressed_certificate_alg(SSL_CONNECTION *sc)
378
2.33k
{
379
#ifndef OPENSSL_NO_COMP_ALG
380
    int *alg = sc->ext.compress_certificate_from_peer;
381
382
    if (sc->s3.tmp.cert == NULL)
383
        return TLSEXT_comp_cert_none;
384
385
    for (; *alg != TLSEXT_comp_cert_none; alg++) {
386
        if (sc->s3.tmp.cert->comp_cert[*alg] != NULL)
387
            return *alg;
388
    }
389
#endif
390
2.33k
    return TLSEXT_comp_cert_none;
391
2.33k
}
392
393
/*
394
 * Should we send a CertificateRequest message?
395
 *
396
 * Valid return values are:
397
 *   1: Yes
398
 *   0: No
399
 */
400
int send_certificate_request(SSL_CONNECTION *s)
401
18.9k
{
402
18.9k
    if (
403
        /* don't request cert unless asked for it: */
404
18.9k
        s->verify_mode & SSL_VERIFY_PEER
405
        /*
406
         * don't request if post-handshake-only unless doing
407
         * post-handshake in TLSv1.3:
408
         */
409
0
        && (!SSL_CONNECTION_IS_TLS13(s)
410
0
            || !(s->verify_mode & SSL_VERIFY_POST_HANDSHAKE)
411
0
            || s->post_handshake_auth == SSL_PHA_REQUEST_PENDING)
412
        /*
413
         * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
414
         * a second time:
415
         */
416
0
        && (s->certreqs_sent < 1 || !(s->verify_mode & SSL_VERIFY_CLIENT_ONCE))
417
        /*
418
         * never request cert in anonymous ciphersuites (see
419
         * section "Certificate request" in SSL 3 drafts and in
420
         * RFC 2246):
421
         */
422
0
        && (!(s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL)
423
            /*
424
             * ... except when the application insists on
425
             * verification (against the specs, but statem_clnt.c accepts
426
             * this for SSL 3)
427
             */
428
0
            || (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
429
        /* don't request certificate for SRP auth */
430
0
        && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aSRP)
431
        /*
432
         * With normal PSK Certificates and Certificate Requests
433
         * are omitted
434
         */
435
0
        && !(s->s3.tmp.new_cipher->algorithm_auth & SSL_aPSK)) {
436
0
        return 1;
437
0
    }
438
439
18.9k
    return 0;
440
18.9k
}
441
442
/*
443
 * Get the OCSP response for the certificate from the chain identified
444
 * chainidx.
445
 * If no OCSP response could be found NULL is returned.
446
 */
447
OCSP_RESPONSE *ossl_get_ocsp_response(SSL_CONNECTION *s, int chainidx)
448
0
{
449
0
    OCSP_RESPONSE *resp = NULL;
450
0
#ifndef OPENSSL_NO_OCSP
451
0
    int i = 0, num = 0;
452
0
    unsigned int len;
453
0
    X509 *x = NULL;
454
0
    STACK_OF(X509) *chain_certs = NULL;
455
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
456
0
    OCSP_BASICRESP *bs = NULL;
457
0
    OCSP_SINGLERESP *sr = NULL;
458
0
    OCSP_CERTID *cid = NULL;
459
0
    OCSP_CERTID *sr_cert_id = NULL;
460
0
    ASN1_OBJECT *cert_id_md_oid;
461
0
    char cert_id_md_txt[OSSL_MAX_NAME_SIZE];
462
0
    EVP_MD *cert_id_md;
463
0
    ASN1_INTEGER *respSerial;
464
0
    ASN1_OCTET_STRING *respIssuerNameHash = NULL;
465
0
    ASN1_OCTET_STRING *certIssuerNameHash = NULL;
466
0
    const X509_NAME *certIssuerName;
467
0
    unsigned char md[EVP_MAX_MD_SIZE];
468
0
    const ASN1_INTEGER *certSerial;
469
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
470
471
    /*
472
     * In TLSv1.3 the caller gives the index of the certificate for which the
473
     * status message should be created.
474
     * Prior to TLSv1.3 the chain index is 0 and the body should contain only
475
     * the status of the server certificate itself.
476
     */
477
0
    SSL_get0_chain_certs(ssl, &chain_certs);
478
479
    /*
480
     * If the certificate chain was built, get the status message for the
481
     * requested certificate specified by chainidx.
482
     * SSL_get0_chain_certs provides certificate chain except the server cert.
483
     *
484
     * if chainidx = 0 the server certificate is requested
485
     * if chainidx > 0 an intermediate certificate is requested
486
     */
487
0
    if (chainidx == 0)
488
0
        x = SSL_get_certificate(ssl);
489
0
    else
490
0
        x = sk_X509_value(chain_certs, chainidx - 1);
491
0
    if (x == NULL)
492
0
        return NULL;
493
494
    /* for a selfsigned certificate there will be no OCSP response */
495
0
    if (X509_self_signed(x, 0))
496
0
        return NULL;
497
498
0
    if ((resp = sk_OCSP_RESPONSE_value(s->ext.ocsp.resp_ex, chainidx)) != NULL) {
499
        /*
500
         * Find the corresponding single OCSP response by comparing the current
501
         * certificate's serial number, and the hash of the current certificate's
502
         * issuer name, to the serial number and issuer name hash in each OCSP
503
         * response received.
504
         */
505
0
        if (OCSP_response_status(resp) == OCSP_RESPONSE_STATUS_SUCCESSFUL) {
506
            /*
507
             * Set a mark for the error queue here to be able to ignore errors
508
             * happening because of test cases.
509
             */
510
0
            ERR_set_mark();
511
0
            bs = OCSP_response_get1_basic(resp);
512
0
            if (bs != NULL && (sr = OCSP_resp_get0(bs, 0)) != NULL) {
513
                /* use the first single response to get the algorithm used */
514
0
                cid = (OCSP_CERTID *)OCSP_SINGLERESP_get0_id(sr);
515
516
                /* determine the md algorithm which was used to create cert id */
517
0
                OCSP_id_get0_info(&respIssuerNameHash, &cert_id_md_oid, NULL, &respSerial, cid);
518
0
                if (cert_id_md_oid != NULL) {
519
0
                    OBJ_obj2txt(cert_id_md_txt, sizeof(cert_id_md_txt), cert_id_md_oid, 0);
520
0
                    cert_id_md = EVP_MD_fetch(sctx->libctx, cert_id_md_txt, sctx->propq);
521
0
                } else {
522
0
                    cert_id_md = EVP_MD_fetch(sctx->libctx, SN_sha1, sctx->propq);
523
0
                }
524
525
0
                if (cert_id_md == NULL) {
526
0
                    OCSP_BASICRESP_free(bs);
527
0
                    ERR_clear_last_mark();
528
0
                    return NULL;
529
0
                }
530
531
                /* get serial number and issuer name hash of the certificate from the chain */
532
0
                certSerial = X509_get0_serialNumber(x);
533
0
                certIssuerName = X509_get_issuer_name(x);
534
0
                certIssuerNameHash = ASN1_OCTET_STRING_new();
535
0
                if (!X509_NAME_digest(certIssuerName, cert_id_md, md, &len) || !(ASN1_OCTET_STRING_set(certIssuerNameHash, md, len))) {
536
0
                    ASN1_OCTET_STRING_free(certIssuerNameHash);
537
0
                    OCSP_BASICRESP_free(bs);
538
0
                    EVP_MD_free(cert_id_md);
539
0
                    ERR_clear_last_mark();
540
0
                    return NULL;
541
0
                }
542
543
0
                num = OCSP_resp_count(bs);
544
0
                for (i = 0; i < num; i++) {
545
0
                    sr = OCSP_resp_get0(bs, i);
546
547
                    /*
548
                     * get the CertID from the OCSP response to compare it with the information
549
                     * from the certificate
550
                     */
551
0
                    sr_cert_id = (OCSP_CERTID *)OCSP_SINGLERESP_get0_id(sr);
552
553
0
                    OCSP_id_get0_info(&respIssuerNameHash, NULL, NULL, &respSerial, sr_cert_id);
554
555
0
                    if (!ASN1_INTEGER_cmp(certSerial, respSerial) && !ASN1_OCTET_STRING_cmp(certIssuerNameHash, respIssuerNameHash))
556
0
                        break;
557
0
                }
558
559
0
                ASN1_OCTET_STRING_free(certIssuerNameHash);
560
0
                OCSP_BASICRESP_free(bs);
561
0
                EVP_MD_free(cert_id_md);
562
563
                /*
564
                 * if we did not find the right single response we return NULL here
565
                 */
566
0
                if (i == num)
567
0
                    resp = NULL;
568
0
            } else {
569
0
                OCSP_BASICRESP_free(bs);
570
0
            }
571
572
            /*
573
             * in a test case a response without a basic response is used the error set
574
             * could be ignored here
575
             */
576
0
            ERR_pop_to_mark();
577
0
        }
578
0
    }
579
0
#endif
580
581
0
    return resp;
582
0
}
583
584
static int do_compressed_cert(SSL_CONNECTION *sc)
585
2.33k
{
586
    /* If we negotiated RPK, we won't attempt to compress it */
587
2.33k
    return sc->ext.server_cert_type == TLSEXT_cert_type_x509
588
2.33k
        && get_compressed_certificate_alg(sc) != TLSEXT_comp_cert_none;
589
2.33k
}
590
591
/*
592
 * ossl_statem_server13_write_transition() works out what handshake state to
593
 * move to next when a TLSv1.3 server is writing messages to be sent to the
594
 * client.
595
 */
596
static WRITE_TRAN ossl_statem_server13_write_transition(SSL_CONNECTION *s)
597
15.8k
{
598
15.8k
    OSSL_STATEM *st = &s->statem;
599
600
    /*
601
     * No case for TLS_ST_BEFORE, because at that stage we have not negotiated
602
     * TLSv1.3 yet, so that is handled by ossl_statem_server_write_transition()
603
     */
604
605
15.8k
    switch (st->hand_state) {
606
0
    default:
607
        /* Shouldn't happen */
608
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
609
0
        return WRITE_TRAN_ERROR;
610
611
0
    case TLS_ST_OK:
612
0
        if (s->key_update != SSL_KEY_UPDATE_NONE) {
613
0
            st->hand_state = TLS_ST_SW_KEY_UPDATE;
614
0
            return WRITE_TRAN_CONTINUE;
615
0
        }
616
0
        if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
617
0
            st->hand_state = TLS_ST_SW_CERT_REQ;
618
0
            return WRITE_TRAN_CONTINUE;
619
0
        }
620
0
        if (s->ext.extra_tickets_expected > 0) {
621
0
            st->hand_state = TLS_ST_SW_SESSION_TICKET;
622
0
            return WRITE_TRAN_CONTINUE;
623
0
        }
624
        /* Try to read from the client instead */
625
0
        return WRITE_TRAN_FINISHED;
626
627
2.21k
    case TLS_ST_SR_CLNT_HELLO:
628
2.21k
        st->hand_state = TLS_ST_SW_SRVR_HELLO;
629
2.21k
        return WRITE_TRAN_CONTINUE;
630
631
2.20k
    case TLS_ST_SW_SRVR_HELLO:
632
2.20k
        if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
633
2.20k
            && s->hello_retry_request != SSL_HRR_COMPLETE)
634
2.14k
            st->hand_state = TLS_ST_SW_CHANGE;
635
57
        else if (s->hello_retry_request == SSL_HRR_PENDING)
636
0
            st->hand_state = TLS_ST_EARLY_DATA;
637
57
        else
638
57
            st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
639
2.20k
        return WRITE_TRAN_CONTINUE;
640
641
2.14k
    case TLS_ST_SW_CHANGE:
642
2.14k
        if (s->hello_retry_request == SSL_HRR_PENDING)
643
435
            st->hand_state = TLS_ST_EARLY_DATA;
644
1.71k
        else
645
1.71k
            st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
646
2.14k
        return WRITE_TRAN_CONTINUE;
647
648
1.77k
    case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
649
1.77k
        if (s->hit)
650
0
            st->hand_state = TLS_ST_SW_FINISHED;
651
1.77k
        else if (send_certificate_request(s))
652
0
            st->hand_state = TLS_ST_SW_CERT_REQ;
653
1.77k
        else if (do_compressed_cert(s))
654
0
            st->hand_state = TLS_ST_SW_COMP_CERT;
655
1.77k
        else
656
1.77k
            st->hand_state = TLS_ST_SW_CERT;
657
658
1.77k
        return WRITE_TRAN_CONTINUE;
659
660
0
    case TLS_ST_SW_CERT_REQ:
661
0
        if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
662
0
            s->post_handshake_auth = SSL_PHA_REQUESTED;
663
0
            st->hand_state = TLS_ST_OK;
664
0
        } else if (do_compressed_cert(s)) {
665
0
            st->hand_state = TLS_ST_SW_COMP_CERT;
666
0
        } else {
667
0
            st->hand_state = TLS_ST_SW_CERT;
668
0
        }
669
0
        return WRITE_TRAN_CONTINUE;
670
671
0
    case TLS_ST_SW_COMP_CERT:
672
1.77k
    case TLS_ST_SW_CERT:
673
1.77k
        st->hand_state = TLS_ST_SW_CERT_VRFY;
674
1.77k
        return WRITE_TRAN_CONTINUE;
675
676
1.77k
    case TLS_ST_SW_CERT_VRFY:
677
1.77k
        st->hand_state = TLS_ST_SW_FINISHED;
678
1.77k
        return WRITE_TRAN_CONTINUE;
679
680
1.77k
    case TLS_ST_SW_FINISHED:
681
1.77k
        st->hand_state = TLS_ST_EARLY_DATA;
682
1.77k
        s->ts_msg_write = ossl_time_now();
683
1.77k
        return WRITE_TRAN_CONTINUE;
684
685
2.20k
    case TLS_ST_EARLY_DATA:
686
2.20k
        return WRITE_TRAN_FINISHED;
687
688
0
    case TLS_ST_SR_FINISHED:
689
0
        s->ts_msg_read = ossl_time_now();
690
        /*
691
         * Technically we have finished the handshake at this point, but we're
692
         * going to remain "in_init" for now and write out any session tickets
693
         * immediately.
694
         */
695
0
        if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
696
0
            s->post_handshake_auth = SSL_PHA_EXT_RECEIVED;
697
0
        } else if (!s->ext.ticket_expected) {
698
            /*
699
             * If we're not going to renew the ticket then we just finish the
700
             * handshake at this point.
701
             */
702
0
            st->hand_state = TLS_ST_OK;
703
0
            return WRITE_TRAN_CONTINUE;
704
0
        }
705
0
        if (s->num_tickets > s->sent_tickets)
706
0
            st->hand_state = TLS_ST_SW_SESSION_TICKET;
707
0
        else
708
0
            st->hand_state = TLS_ST_OK;
709
0
        return WRITE_TRAN_CONTINUE;
710
711
0
    case TLS_ST_SR_KEY_UPDATE:
712
0
    case TLS_ST_SW_KEY_UPDATE:
713
0
        st->hand_state = TLS_ST_OK;
714
0
        return WRITE_TRAN_CONTINUE;
715
716
0
    case TLS_ST_SW_SESSION_TICKET:
717
        /* In a resumption we only ever send a maximum of one new ticket.
718
         * Following an initial handshake we send the number of tickets we have
719
         * been configured for.
720
         */
721
0
        if (!SSL_IS_FIRST_HANDSHAKE(s) && s->ext.extra_tickets_expected > 0) {
722
0
            return WRITE_TRAN_CONTINUE;
723
0
        } else if (s->hit || s->num_tickets <= s->sent_tickets) {
724
            /* We've written enough tickets out. */
725
0
            st->hand_state = TLS_ST_OK;
726
0
        }
727
0
        return WRITE_TRAN_CONTINUE;
728
15.8k
    }
729
15.8k
}
730
731
/*
732
 * ossl_statem_server_write_transition() works out what handshake state to move
733
 * to next when the server is writing messages to be sent to the client.
734
 */
735
WRITE_TRAN ossl_statem_server_write_transition(SSL_CONNECTION *s)
736
188k
{
737
188k
    OSSL_STATEM *st = &s->statem;
738
739
    /*
740
     * Note that before the ClientHello we don't know what version we are going
741
     * to negotiate yet, so we don't take this branch until later
742
     */
743
744
188k
    if (SSL_CONNECTION_IS_TLS13(s))
745
15.8k
        return ossl_statem_server13_write_transition(s);
746
747
172k
    switch (st->hand_state) {
748
0
    default:
749
        /* Shouldn't happen */
750
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
751
0
        return WRITE_TRAN_ERROR;
752
753
34.6k
    case TLS_ST_OK:
754
34.6k
        if (st->request_state == TLS_ST_SW_HELLO_REQ) {
755
            /* We must be trying to renegotiate */
756
0
            st->hand_state = TLS_ST_SW_HELLO_REQ;
757
0
            st->request_state = TLS_ST_BEFORE;
758
0
            return WRITE_TRAN_CONTINUE;
759
0
        }
760
        /* Must be an incoming ClientHello */
761
34.6k
        if (!tls_setup_handshake(s)) {
762
            /* SSLfatal() already called */
763
0
            return WRITE_TRAN_ERROR;
764
0
        }
765
        /* Fall through */
766
767
67.3k
    case TLS_ST_BEFORE:
768
        /* Just go straight to trying to read from the client */
769
67.3k
        return WRITE_TRAN_FINISHED;
770
771
0
    case TLS_ST_SW_HELLO_REQ:
772
0
        st->hand_state = TLS_ST_OK;
773
0
        return WRITE_TRAN_CONTINUE;
774
775
49.8k
    case TLS_ST_SR_CLNT_HELLO:
776
49.8k
        if (SSL_CONNECTION_IS_DTLS(s) && !s->d1->cookie_verified
777
7.29k
            && (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE)) {
778
0
            st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
779
49.8k
        } else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
780
            /* We must have rejected the renegotiation */
781
34.2k
            st->hand_state = TLS_ST_OK;
782
34.2k
            return WRITE_TRAN_CONTINUE;
783
34.2k
        } else {
784
15.5k
            st->hand_state = TLS_ST_SW_SRVR_HELLO;
785
15.5k
        }
786
15.5k
        return WRITE_TRAN_CONTINUE;
787
788
0
    case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
789
0
        return WRITE_TRAN_FINISHED;
790
791
15.5k
    case TLS_ST_SW_SRVR_HELLO:
792
15.5k
        if (s->hit) {
793
129
            if (s->ext.ticket_expected)
794
0
                st->hand_state = TLS_ST_SW_SESSION_TICKET;
795
129
            else
796
129
                st->hand_state = TLS_ST_SW_CHANGE;
797
15.4k
        } else {
798
            /* Check if it is anon DH or anon ECDH, */
799
            /* normal PSK or SRP */
800
15.4k
            if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
801
13.9k
                st->hand_state = TLS_ST_SW_CERT;
802
13.9k
            } else if (send_server_key_exchange(s)) {
803
1.45k
                st->hand_state = TLS_ST_SW_KEY_EXCH;
804
1.45k
            } else if (send_certificate_request(s)) {
805
0
                st->hand_state = TLS_ST_SW_CERT_REQ;
806
0
            } else {
807
0
                st->hand_state = TLS_ST_SW_SRVR_DONE;
808
0
            }
809
15.4k
        }
810
15.5k
        return WRITE_TRAN_CONTINUE;
811
812
13.9k
    case TLS_ST_SW_CERT:
813
13.9k
        if (s->ext.status_expected) {
814
0
            st->hand_state = TLS_ST_SW_CERT_STATUS;
815
0
            return WRITE_TRAN_CONTINUE;
816
0
        }
817
        /* Fall through */
818
819
13.9k
    case TLS_ST_SW_CERT_STATUS:
820
13.9k
        if (send_server_key_exchange(s)) {
821
5.53k
            st->hand_state = TLS_ST_SW_KEY_EXCH;
822
5.53k
            return WRITE_TRAN_CONTINUE;
823
5.53k
        }
824
        /* Fall through */
825
826
15.4k
    case TLS_ST_SW_KEY_EXCH:
827
15.4k
        if (send_certificate_request(s)) {
828
0
            st->hand_state = TLS_ST_SW_CERT_REQ;
829
0
            return WRITE_TRAN_CONTINUE;
830
0
        }
831
        /* Fall through */
832
833
15.4k
    case TLS_ST_SW_CERT_REQ:
834
15.4k
        st->hand_state = TLS_ST_SW_SRVR_DONE;
835
15.4k
        return WRITE_TRAN_CONTINUE;
836
837
15.4k
    case TLS_ST_SW_SRVR_DONE:
838
15.4k
        s->ts_msg_write = ossl_time_now();
839
15.4k
        return WRITE_TRAN_FINISHED;
840
841
965
    case TLS_ST_SR_FINISHED:
842
965
        s->ts_msg_read = ossl_time_now();
843
965
        if (s->hit) {
844
0
            st->hand_state = TLS_ST_OK;
845
0
            return WRITE_TRAN_CONTINUE;
846
965
        } else if (s->ext.ticket_expected) {
847
93
            st->hand_state = TLS_ST_SW_SESSION_TICKET;
848
872
        } else {
849
872
            st->hand_state = TLS_ST_SW_CHANGE;
850
872
        }
851
965
        return WRITE_TRAN_CONTINUE;
852
853
93
    case TLS_ST_SW_SESSION_TICKET:
854
93
        st->hand_state = TLS_ST_SW_CHANGE;
855
93
        return WRITE_TRAN_CONTINUE;
856
857
1.09k
    case TLS_ST_SW_CHANGE:
858
1.09k
        st->hand_state = TLS_ST_SW_FINISHED;
859
1.09k
        return WRITE_TRAN_CONTINUE;
860
861
1.09k
    case TLS_ST_SW_FINISHED:
862
1.09k
        if (s->hit) {
863
129
            return WRITE_TRAN_FINISHED;
864
129
        }
865
965
        st->hand_state = TLS_ST_OK;
866
965
        return WRITE_TRAN_CONTINUE;
867
172k
    }
868
172k
}
869
870
/*
871
 * Perform any pre work that needs to be done prior to sending a message from
872
 * the server to the client.
873
 */
874
WORK_STATE ossl_statem_server_pre_work(SSL_CONNECTION *s, WORK_STATE wst)
875
82.9k
{
876
82.9k
    OSSL_STATEM *st = &s->statem;
877
82.9k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
878
879
82.9k
    switch (st->hand_state) {
880
20.9k
    default:
881
        /* No pre work to be done */
882
20.9k
        break;
883
884
20.9k
    case TLS_ST_SW_HELLO_REQ:
885
0
        s->shutdown = 0;
886
0
        if (SSL_CONNECTION_IS_DTLS(s))
887
0
            dtls1_clear_sent_buffer(s);
888
0
        break;
889
890
0
    case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
891
0
        s->shutdown = 0;
892
0
        if (SSL_CONNECTION_IS_DTLS(s)) {
893
0
            dtls1_clear_sent_buffer(s);
894
            /* We don't buffer this message so don't use the timer */
895
0
            st->use_timer = 0;
896
0
        }
897
0
        break;
898
899
12.6k
    case TLS_ST_SW_SRVR_HELLO:
900
12.6k
        if (SSL_CONNECTION_IS_DTLS(s)) {
901
            /*
902
             * Messages we write from now on should be buffered and
903
             * retransmitted if necessary, so we need to use the timer now
904
             */
905
4.94k
            st->use_timer = 1;
906
4.94k
        }
907
12.6k
        break;
908
909
10.9k
    case TLS_ST_SW_SRVR_DONE:
910
#ifndef OPENSSL_NO_SCTP
911
        if (SSL_CONNECTION_IS_DTLS(s) && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
912
            /* Calls SSLfatal() as required */
913
            return dtls_wait_for_dry(s);
914
        }
915
#endif
916
10.9k
        return WORK_FINISHED_CONTINUE;
917
918
80
    case TLS_ST_SW_SESSION_TICKET:
919
80
        if (SSL_CONNECTION_IS_TLS13(s) && s->sent_tickets == 0
920
0
            && s->ext.extra_tickets_expected == 0) {
921
            /*
922
             * Actually this is the end of the handshake, but we're going
923
             * straight into writing the session ticket out. So we finish off
924
             * the handshake, but keep the various buffers active.
925
             *
926
             * Calls SSLfatal as required.
927
             */
928
0
            return tls_finish_handshake(s, wst, 0, 0);
929
0
        }
930
80
        if (SSL_CONNECTION_IS_DTLS(s)) {
931
            /*
932
             * We're into the last flight. We don't retransmit the last flight
933
             * unless we need to, so we don't use the timer
934
             */
935
0
            st->use_timer = 0;
936
0
        }
937
80
        break;
938
939
2.31k
    case TLS_ST_SW_CHANGE:
940
2.31k
        if (SSL_CONNECTION_IS_TLS13(s))
941
1.57k
            break;
942
        /* Writes to s->session are only safe for initial handshakes */
943
749
        if (s->session->cipher == NULL) {
944
0
            s->session->cipher = s->s3.tmp.new_cipher;
945
749
        } else if (s->session->cipher != s->s3.tmp.new_cipher) {
946
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
947
0
            return WORK_ERROR;
948
0
        }
949
749
        if (!ssl->method->ssl3_enc->setup_key_block(s)) {
950
            /* SSLfatal() already called */
951
0
            return WORK_ERROR;
952
0
        }
953
749
        if (SSL_CONNECTION_IS_DTLS(s)) {
954
            /*
955
             * We're into the last flight. We don't retransmit the last flight
956
             * unless we need to, so we don't use the timer. This might have
957
             * already been set to 0 if we sent a NewSessionTicket message,
958
             * but we'll set it again here in case we didn't.
959
             */
960
0
            st->use_timer = 0;
961
0
        }
962
749
        return WORK_FINISHED_CONTINUE;
963
964
1.62k
    case TLS_ST_EARLY_DATA:
965
1.62k
        if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING
966
1.04k
            && (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
967
1.04k
            return WORK_FINISHED_CONTINUE;
968
969
        /*
970
         * In QUIC with 0-RTT we just carry on when otherwise we would stop
971
         * to allow the server to read early data
972
         */
973
578
        if (SSL_NO_EOED(s) && s->ext.early_data == SSL_EARLY_DATA_ACCEPTED
974
0
            && s->early_data_state != SSL_EARLY_DATA_FINISHED_READING) {
975
0
            s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
976
0
            if (!ssl->method->ssl3_enc->change_cipher_state(s, SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
977
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
978
0
                return WORK_ERROR;
979
0
            }
980
0
            return WORK_FINISHED_SWAP;
981
0
        }
982
        /* Fall through */
983
984
34.9k
    case TLS_ST_OK:
985
        /* Calls SSLfatal() as required */
986
34.9k
        return tls_finish_handshake(s, wst, 1, 1);
987
82.9k
    }
988
989
35.2k
    return WORK_FINISHED_CONTINUE;
990
82.9k
}
991
992
static ossl_inline int conn_is_closed(void)
993
0
{
994
0
    switch (get_last_sys_error()) {
995
0
#if defined(EPIPE)
996
0
    case EPIPE:
997
0
        return 1;
998
0
#endif
999
0
#if defined(ECONNRESET)
1000
0
    case ECONNRESET:
1001
0
        return 1;
1002
0
#endif
1003
#if defined(WSAECONNRESET)
1004
    case WSAECONNRESET:
1005
        return 1;
1006
#endif
1007
0
    default:
1008
0
        return 0;
1009
0
    }
1010
0
}
1011
1012
/*
1013
 * Perform any work that needs to be done after sending a message from the
1014
 * server to the client.
1015
 */
1016
WORK_STATE ossl_statem_server_post_work(SSL_CONNECTION *s, WORK_STATE wst)
1017
47.9k
{
1018
47.9k
    OSSL_STATEM *st = &s->statem;
1019
47.9k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1020
1021
47.9k
    s->init_num = 0;
1022
1023
47.9k
    switch (st->hand_state) {
1024
18.6k
    default:
1025
        /* No post work to be done */
1026
18.6k
        break;
1027
1028
18.6k
    case TLS_ST_SW_HELLO_REQ:
1029
0
        if (statem_flush(s) != 1)
1030
0
            return WORK_MORE_A;
1031
0
        if (!ssl3_init_finished_mac(s)) {
1032
            /* SSLfatal() already called */
1033
0
            return WORK_ERROR;
1034
0
        }
1035
0
        break;
1036
1037
0
    case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1038
0
        if (statem_flush(s) != 1)
1039
0
            return WORK_MORE_A;
1040
        /* HelloVerifyRequest resets Finished MAC */
1041
0
        if (s->version != DTLS1_BAD_VER && !ssl3_init_finished_mac(s)) {
1042
            /* SSLfatal() already called */
1043
0
            return WORK_ERROR;
1044
0
        }
1045
        /*
1046
         * The next message should be another ClientHello which we need to
1047
         * treat like it was the first packet
1048
         */
1049
0
        s->first_packet = 1;
1050
0
        break;
1051
1052
12.6k
    case TLS_ST_SW_SRVR_HELLO:
1053
12.6k
        if (SSL_CONNECTION_IS_TLS13(s)
1054
1.62k
            && s->hello_retry_request == SSL_HRR_PENDING) {
1055
329
            if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0
1056
0
                && statem_flush(s) != 1)
1057
0
                return WORK_MORE_A;
1058
329
            break;
1059
329
        }
1060
#ifndef OPENSSL_NO_SCTP
1061
        if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {
1062
            unsigned char sctpauthkey[64];
1063
            char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1064
            size_t labellen;
1065
1066
            /*
1067
             * Add new shared key for SCTP-Auth, will be ignored if no
1068
             * SCTP used.
1069
             */
1070
            memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1071
                sizeof(DTLS1_SCTP_AUTH_LABEL));
1072
1073
            /* Don't include the terminating zero. */
1074
            labellen = sizeof(labelbuffer) - 1;
1075
            if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
1076
                labellen += 1;
1077
1078
            if (SSL_export_keying_material(ssl, sctpauthkey,
1079
                    sizeof(sctpauthkey), labelbuffer,
1080
                    labellen, NULL, 0,
1081
                    0)
1082
                <= 0) {
1083
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1084
                return WORK_ERROR;
1085
            }
1086
1087
            BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1088
                sizeof(sctpauthkey), sctpauthkey);
1089
        }
1090
#endif
1091
12.3k
        if (!SSL_CONNECTION_IS_TLS13(s)
1092
1.29k
            || ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
1093
1.29k
                && s->hello_retry_request != SSL_HRR_COMPLETE))
1094
12.2k
            break;
1095
        /* Fall through */
1096
1097
2.37k
    case TLS_ST_SW_CHANGE:
1098
2.37k
        if (s->hello_retry_request == SSL_HRR_PENDING) {
1099
329
            if (!statem_flush(s))
1100
0
                return WORK_MORE_A;
1101
329
            break;
1102
329
        }
1103
1104
2.04k
        if (SSL_CONNECTION_IS_TLS13(s)) {
1105
1.29k
            if (!ssl->method->ssl3_enc->setup_key_block(s)
1106
1.29k
                || !tls13_store_handshake_traffic_hash(s)
1107
1.29k
                || !ssl->method->ssl3_enc->change_cipher_state(s,
1108
1.29k
                    SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
1109
                /* SSLfatal() already called */
1110
0
                return WORK_ERROR;
1111
0
            }
1112
1113
1.29k
            if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
1114
1.29k
                && !ssl->method->ssl3_enc->change_cipher_state(s,
1115
1.29k
                    SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
1116
                /* SSLfatal() already called */
1117
0
                return WORK_ERROR;
1118
0
            }
1119
            /*
1120
             * We don't yet know whether the next record we are going to receive
1121
             * is an unencrypted alert, an encrypted alert, or an encrypted
1122
             * handshake message. We temporarily tolerate unencrypted alerts.
1123
             */
1124
1.29k
            if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
1125
1.29k
                s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 1);
1126
1.29k
            break;
1127
1.29k
        }
1128
1129
#ifndef OPENSSL_NO_SCTP
1130
        if (SSL_CONNECTION_IS_DTLS(s) && !s->hit) {
1131
            /*
1132
             * Change to new shared key of SCTP-Auth, will be ignored if
1133
             * no SCTP used.
1134
             */
1135
            BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1136
                0, NULL);
1137
        }
1138
#endif
1139
749
        if (!ssl->method->ssl3_enc->change_cipher_state(s,
1140
749
                SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
1141
            /* SSLfatal() already called */
1142
0
            return WORK_ERROR;
1143
0
        }
1144
749
        break;
1145
1146
10.9k
    case TLS_ST_SW_SRVR_DONE:
1147
10.9k
        if (statem_flush(s) != 1)
1148
0
            return WORK_MORE_A;
1149
10.9k
        break;
1150
1151
10.9k
    case TLS_ST_SW_FINISHED:
1152
2.04k
        if (statem_flush(s) != 1)
1153
0
            return WORK_MORE_A;
1154
#ifndef OPENSSL_NO_SCTP
1155
        if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {
1156
            /*
1157
             * Change to new shared key of SCTP-Auth, will be ignored if
1158
             * no SCTP used.
1159
             */
1160
            BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
1161
                0, NULL);
1162
        }
1163
#endif
1164
2.04k
        if (SSL_CONNECTION_IS_TLS13(s)) {
1165
            /* TLS 1.3 gets the secret size from the handshake md */
1166
1.29k
            size_t dummy;
1167
1.29k
            if (!ssl->method->ssl3_enc->generate_master_secret(s,
1168
1.29k
                    s->master_secret, s->handshake_secret, 0,
1169
1.29k
                    &dummy)
1170
1.29k
                || !tls13_store_server_finished_hash(s)
1171
1.29k
                || !ssl->method->ssl3_enc->change_cipher_state(s,
1172
1.29k
                    SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
1173
                /* SSLfatal() already called */
1174
0
                return WORK_ERROR;
1175
1.29k
        }
1176
2.04k
        break;
1177
1178
2.04k
    case TLS_ST_SW_CERT_REQ:
1179
0
        if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
1180
0
            if (statem_flush(s) != 1)
1181
0
                return WORK_MORE_A;
1182
0
        } else {
1183
0
            if (!SSL_CONNECTION_IS_TLS13(s)
1184
0
                || (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
1185
0
                s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
1186
0
        }
1187
0
        break;
1188
1189
1.29k
    case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1190
1.29k
        if (!s->hit && !send_certificate_request(s)) {
1191
1.29k
            if (!SSL_CONNECTION_IS_TLS13(s)
1192
1.29k
                || (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
1193
0
                s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
1194
1.29k
        }
1195
1.29k
        break;
1196
1197
0
    case TLS_ST_SW_KEY_UPDATE:
1198
0
        if (statem_flush(s) != 1)
1199
0
            return WORK_MORE_A;
1200
0
        if (!tls13_update_key(s, 1)) {
1201
            /* SSLfatal() already called */
1202
0
            return WORK_ERROR;
1203
0
        }
1204
0
        break;
1205
1206
80
    case TLS_ST_SW_SESSION_TICKET:
1207
80
        clear_sys_error();
1208
80
        if (SSL_CONNECTION_IS_TLS13(s) && statem_flush(s) != 1) {
1209
0
            if (SSL_get_error(ssl, 0) == SSL_ERROR_SYSCALL
1210
0
                && conn_is_closed()) {
1211
                /*
1212
                 * We ignore connection closed errors in TLSv1.3 when sending a
1213
                 * NewSessionTicket and behave as if we were successful. This is
1214
                 * so that we are still able to read data sent to us by a client
1215
                 * that closes soon after the end of the handshake without
1216
                 * waiting to read our post-handshake NewSessionTickets.
1217
                 */
1218
0
                s->rwstate = SSL_NOTHING;
1219
0
                break;
1220
0
            }
1221
1222
0
            return WORK_MORE_A;
1223
0
        }
1224
80
        ERR_clear_last_mark();
1225
80
        break;
1226
47.9k
    }
1227
1228
47.9k
    return WORK_FINISHED_CONTINUE;
1229
47.9k
}
1230
1231
/*
1232
 * Get the message construction function and message type for sending from the
1233
 * server
1234
 *
1235
 * Valid return values are:
1236
 *   1: Success
1237
 *   0: Error
1238
 */
1239
int ossl_statem_server_construct_message(SSL_CONNECTION *s,
1240
    confunc_f *confunc, int *mt)
1241
67.0k
{
1242
67.0k
    OSSL_STATEM *st = &s->statem;
1243
1244
67.0k
    switch (st->hand_state) {
1245
0
    default:
1246
        /* Shouldn't happen */
1247
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
1248
0
        return 0;
1249
1250
3.24k
    case TLS_ST_SW_CHANGE:
1251
3.24k
        if (SSL_CONNECTION_IS_DTLS(s))
1252
0
            *confunc = dtls_construct_change_cipher_spec;
1253
3.24k
        else
1254
3.24k
            *confunc = tls_construct_change_cipher_spec;
1255
3.24k
        *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1256
3.24k
        break;
1257
1258
0
    case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1259
0
        *confunc = dtls_construct_hello_verify_request;
1260
0
        *mt = DTLS1_MT_HELLO_VERIFY_REQUEST;
1261
0
        break;
1262
1263
0
    case TLS_ST_SW_HELLO_REQ:
1264
        /* No construction function needed */
1265
0
        *confunc = NULL;
1266
0
        *mt = SSL3_MT_HELLO_REQUEST;
1267
0
        break;
1268
1269
17.7k
    case TLS_ST_SW_SRVR_HELLO:
1270
17.7k
        *confunc = tls_construct_server_hello;
1271
17.7k
        *mt = SSL3_MT_SERVER_HELLO;
1272
17.7k
        break;
1273
1274
15.7k
    case TLS_ST_SW_CERT:
1275
15.7k
        *confunc = tls_construct_server_certificate;
1276
15.7k
        *mt = SSL3_MT_CERTIFICATE;
1277
15.7k
        break;
1278
1279
#ifndef OPENSSL_NO_COMP_ALG
1280
    case TLS_ST_SW_COMP_CERT:
1281
        *confunc = tls_construct_server_compressed_certificate;
1282
        *mt = SSL3_MT_COMPRESSED_CERTIFICATE;
1283
        break;
1284
#endif
1285
1286
1.77k
    case TLS_ST_SW_CERT_VRFY:
1287
1.77k
        *confunc = tls_construct_cert_verify;
1288
1.77k
        *mt = SSL3_MT_CERTIFICATE_VERIFY;
1289
1.77k
        break;
1290
1291
6.99k
    case TLS_ST_SW_KEY_EXCH:
1292
6.99k
        *confunc = tls_construct_server_key_exchange;
1293
6.99k
        *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
1294
6.99k
        break;
1295
1296
0
    case TLS_ST_SW_CERT_REQ:
1297
0
        *confunc = tls_construct_certificate_request;
1298
0
        *mt = SSL3_MT_CERTIFICATE_REQUEST;
1299
0
        break;
1300
1301
15.4k
    case TLS_ST_SW_SRVR_DONE:
1302
15.4k
        *confunc = tls_construct_server_done;
1303
15.4k
        *mt = SSL3_MT_SERVER_DONE;
1304
15.4k
        break;
1305
1306
93
    case TLS_ST_SW_SESSION_TICKET:
1307
93
        *confunc = tls_construct_new_session_ticket;
1308
93
        *mt = SSL3_MT_NEWSESSION_TICKET;
1309
93
        break;
1310
1311
0
    case TLS_ST_SW_CERT_STATUS:
1312
0
        *confunc = tls_construct_cert_status;
1313
0
        *mt = SSL3_MT_CERTIFICATE_STATUS;
1314
0
        break;
1315
1316
2.86k
    case TLS_ST_SW_FINISHED:
1317
2.86k
        *confunc = tls_construct_finished;
1318
2.86k
        *mt = SSL3_MT_FINISHED;
1319
2.86k
        break;
1320
1321
1.30k
    case TLS_ST_EARLY_DATA:
1322
1.30k
        *confunc = NULL;
1323
1.30k
        *mt = SSL3_MT_DUMMY;
1324
1.30k
        break;
1325
1326
1.77k
    case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1327
1.77k
        *confunc = tls_construct_encrypted_extensions;
1328
1.77k
        *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
1329
1.77k
        break;
1330
1331
0
    case TLS_ST_SW_KEY_UPDATE:
1332
0
        *confunc = tls_construct_key_update;
1333
0
        *mt = SSL3_MT_KEY_UPDATE;
1334
0
        break;
1335
67.0k
    }
1336
1337
67.0k
    return 1;
1338
67.0k
}
1339
1340
/*
1341
 * Maximum size (excluding the Handshake header) of a ClientHello message,
1342
 * calculated as follows:
1343
 *
1344
 *  2 + # client_version
1345
 *  32 + # only valid length for random
1346
 *  1 + # length of session_id
1347
 *  32 + # maximum size for session_id
1348
 *  2 + # length of cipher suites
1349
 *  2^16-2 + # maximum length of cipher suites array
1350
 *  1 + # length of compression_methods
1351
 *  2^8-1 + # maximum length of compression methods
1352
 *  2 + # length of extensions
1353
 *  2^16-1 # maximum length of extensions
1354
 */
1355
61.7k
#define CLIENT_HELLO_MAX_LENGTH 131396
1356
1357
11.2k
#define CLIENT_KEY_EXCH_MAX_LENGTH 2048
1358
0
#define NEXT_PROTO_MAX_LENGTH 514
1359
1360
/*
1361
 * Returns the maximum allowed length for the current message that we are
1362
 * reading. Excludes the message header.
1363
 */
1364
size_t ossl_statem_server_max_message_size(SSL_CONNECTION *s)
1365
80.7k
{
1366
80.7k
    OSSL_STATEM *st = &s->statem;
1367
1368
80.7k
    switch (st->hand_state) {
1369
0
    default:
1370
        /* Shouldn't happen */
1371
0
        return 0;
1372
1373
61.7k
    case TLS_ST_SR_CLNT_HELLO:
1374
61.7k
        return CLIENT_HELLO_MAX_LENGTH;
1375
1376
0
    case TLS_ST_SR_END_OF_EARLY_DATA:
1377
0
        return END_OF_EARLY_DATA_MAX_LENGTH;
1378
1379
0
    case TLS_ST_SR_COMP_CERT:
1380
0
    case TLS_ST_SR_CERT:
1381
0
        return s->max_cert_list;
1382
1383
11.2k
    case TLS_ST_SR_KEY_EXCH:
1384
11.2k
        return CLIENT_KEY_EXCH_MAX_LENGTH;
1385
1386
0
    case TLS_ST_SR_CERT_VRFY:
1387
0
        return CERTIFICATE_VERIFY_MAX_LENGTH;
1388
1389
0
#ifndef OPENSSL_NO_NEXTPROTONEG
1390
0
    case TLS_ST_SR_NEXT_PROTO:
1391
0
        return NEXT_PROTO_MAX_LENGTH;
1392
0
#endif
1393
1394
6.68k
    case TLS_ST_SR_CHANGE:
1395
6.68k
        return CCS_MAX_LENGTH;
1396
1397
1.02k
    case TLS_ST_SR_FINISHED:
1398
1.02k
        return FINISHED_MAX_LENGTH;
1399
1400
0
    case TLS_ST_SR_KEY_UPDATE:
1401
0
        return KEY_UPDATE_MAX_LENGTH;
1402
80.7k
    }
1403
80.7k
}
1404
1405
/*
1406
 * Process a message that the server has received from the client.
1407
 */
1408
MSG_PROCESS_RETURN ossl_statem_server_process_message(SSL_CONNECTION *s,
1409
    PACKET *pkt)
1410
79.7k
{
1411
79.7k
    OSSL_STATEM *st = &s->statem;
1412
1413
79.7k
    switch (st->hand_state) {
1414
0
    default:
1415
        /* Shouldn't happen */
1416
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1417
0
        return MSG_PROCESS_ERROR;
1418
1419
60.9k
    case TLS_ST_SR_CLNT_HELLO:
1420
60.9k
        return tls_process_client_hello(s, pkt);
1421
1422
0
    case TLS_ST_SR_END_OF_EARLY_DATA:
1423
0
        return tls_process_end_of_early_data(s, pkt);
1424
1425
0
    case TLS_ST_SR_CERT:
1426
0
        return tls_process_client_certificate(s, pkt);
1427
1428
#ifndef OPENSSL_NO_COMP_ALG
1429
    case TLS_ST_SR_COMP_CERT:
1430
        return tls_process_client_compressed_certificate(s, pkt);
1431
#endif
1432
1433
11.1k
    case TLS_ST_SR_KEY_EXCH:
1434
11.1k
        return tls_process_client_key_exchange(s, pkt);
1435
1436
0
    case TLS_ST_SR_CERT_VRFY:
1437
0
        return tls_process_cert_verify(s, pkt);
1438
1439
0
#ifndef OPENSSL_NO_NEXTPROTONEG
1440
0
    case TLS_ST_SR_NEXT_PROTO:
1441
0
        return tls_process_next_proto(s, pkt);
1442
0
#endif
1443
1444
6.67k
    case TLS_ST_SR_CHANGE:
1445
6.67k
        return tls_process_change_cipher_spec(s, pkt);
1446
1447
990
    case TLS_ST_SR_FINISHED:
1448
990
        return tls_process_finished(s, pkt);
1449
1450
0
    case TLS_ST_SR_KEY_UPDATE:
1451
0
        return tls_process_key_update(s, pkt);
1452
79.7k
    }
1453
79.7k
}
1454
1455
/*
1456
 * Perform any further processing required following the receipt of a message
1457
 * from the client
1458
 */
1459
WORK_STATE ossl_statem_server_post_process_message(SSL_CONNECTION *s,
1460
    WORK_STATE wst)
1461
35.4k
{
1462
35.4k
    OSSL_STATEM *st = &s->statem;
1463
1464
35.4k
    switch (st->hand_state) {
1465
0
    default:
1466
        /* Shouldn't happen */
1467
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1468
0
        return WORK_ERROR;
1469
1470
25.5k
    case TLS_ST_SR_CLNT_HELLO:
1471
25.5k
        return tls_post_process_client_hello(s, wst);
1472
1473
9.93k
    case TLS_ST_SR_KEY_EXCH:
1474
9.93k
        return tls_post_process_client_key_exchange(s, wst);
1475
35.4k
    }
1476
35.4k
}
1477
1478
#ifndef OPENSSL_NO_SRP
1479
/* Returns 1 on success, 0 for retryable error, -1 for fatal error */
1480
static int ssl_check_srp_ext_ClientHello(SSL_CONNECTION *s)
1481
23.4k
{
1482
23.4k
    int ret;
1483
23.4k
    int al = SSL_AD_UNRECOGNIZED_NAME;
1484
1485
23.4k
    if ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) && (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
1486
0
        if (s->srp_ctx.login == NULL) {
1487
            /*
1488
             * RFC 5054 says SHOULD reject, we do so if There is no srp
1489
             * login name
1490
             */
1491
0
            SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
1492
0
                SSL_R_PSK_IDENTITY_NOT_FOUND);
1493
0
            return -1;
1494
0
        } else {
1495
0
            ret = ssl_srp_server_param_with_username_intern(s, &al);
1496
0
            if (ret < 0)
1497
0
                return 0;
1498
0
            if (ret == SSL3_AL_FATAL) {
1499
0
                SSLfatal(s, al,
1500
0
                    al == SSL_AD_UNKNOWN_PSK_IDENTITY
1501
0
                        ? SSL_R_PSK_IDENTITY_NOT_FOUND
1502
0
                        : SSL_R_CLIENTHELLO_TLSEXT);
1503
0
                return -1;
1504
0
            }
1505
0
        }
1506
0
    }
1507
23.4k
    return 1;
1508
23.4k
}
1509
#endif
1510
1511
int dtls_raw_hello_verify_request(WPACKET *pkt, unsigned char *cookie,
1512
    size_t cookie_len)
1513
0
{
1514
    /* Always use DTLS 1.0 version: see RFC 6347 */
1515
0
    if (!WPACKET_put_bytes_u16(pkt, DTLS1_VERSION)
1516
0
        || !WPACKET_sub_memcpy_u8(pkt, cookie, cookie_len))
1517
0
        return 0;
1518
1519
0
    return 1;
1520
0
}
1521
1522
CON_FUNC_RETURN dtls_construct_hello_verify_request(SSL_CONNECTION *s,
1523
    WPACKET *pkt)
1524
0
{
1525
0
    unsigned int cookie_leni;
1526
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1527
1528
0
    if (sctx->app_gen_cookie_cb == NULL
1529
0
        || sctx->app_gen_cookie_cb(SSL_CONNECTION_GET_USER_SSL(s), s->d1->cookie,
1530
0
               &cookie_leni)
1531
0
            == 0
1532
0
        || cookie_leni > sizeof(s->d1->cookie)) {
1533
0
        SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
1534
0
        return CON_FUNC_ERROR;
1535
0
    }
1536
0
    s->d1->cookie_len = cookie_leni;
1537
1538
0
    if (!dtls_raw_hello_verify_request(pkt, s->d1->cookie,
1539
0
            s->d1->cookie_len)) {
1540
0
        SSLfatal(s, SSL_AD_NO_ALERT, ERR_R_INTERNAL_ERROR);
1541
0
        return CON_FUNC_ERROR;
1542
0
    }
1543
1544
0
    return CON_FUNC_SUCCESS;
1545
0
}
1546
1547
/*-
1548
 * ssl_check_for_safari attempts to fingerprint Safari using OS X
1549
 * SecureTransport using the TLS extension block in |hello|.
1550
 * Safari, since 10.6, sends exactly these extensions, in this order:
1551
 *   SNI,
1552
 *   elliptic_curves
1553
 *   ec_point_formats
1554
 *   signature_algorithms (for TLSv1.2 only)
1555
 *
1556
 * We wish to fingerprint Safari because they broke ECDHE-ECDSA support in 10.8,
1557
 * but they advertise support. So enabling ECDHE-ECDSA ciphers breaks them.
1558
 * Sadly we cannot differentiate 10.6, 10.7 and 10.8.4 (which work), from
1559
 * 10.8..10.8.3 (which don't work).
1560
 */
1561
static void ssl_check_for_safari(SSL_CONNECTION *s,
1562
    const CLIENTHELLO_MSG *hello)
1563
0
{
1564
0
    static const unsigned char kSafariExtensionsBlock[] = {
1565
0
        0x00,
1566
0
        0x0a, /* elliptic_curves extension */
1567
0
        0x00,
1568
0
        0x08, /* 8 bytes */
1569
0
        0x00,
1570
0
        0x06, /* 6 bytes of curve ids */
1571
0
        0x00,
1572
0
        0x17, /* P-256 */
1573
0
        0x00,
1574
0
        0x18, /* P-384 */
1575
0
        0x00,
1576
0
        0x19, /* P-521 */
1577
1578
0
        0x00,
1579
0
        0x0b, /* ec_point_formats */
1580
0
        0x00,
1581
0
        0x02, /* 2 bytes */
1582
0
        0x01, /* 1 point format */
1583
0
        0x00, /* uncompressed */
1584
        /* The following is only present in TLS 1.2 */
1585
0
        0x00,
1586
0
        0x0d, /* signature_algorithms */
1587
0
        0x00,
1588
0
        0x0c, /* 12 bytes */
1589
0
        0x00,
1590
0
        0x0a, /* 10 bytes */
1591
0
        0x05,
1592
0
        0x01, /* SHA-384/RSA */
1593
0
        0x04,
1594
0
        0x01, /* SHA-256/RSA */
1595
0
        0x02,
1596
0
        0x01, /* SHA-1/RSA */
1597
0
        0x04,
1598
0
        0x03, /* SHA-256/ECDSA */
1599
0
        0x02,
1600
0
        0x03, /* SHA-1/ECDSA */
1601
0
    };
1602
    /* Length of the common prefix (first two extensions). */
1603
0
    static const size_t kSafariCommonExtensionsLength = 18;
1604
0
    unsigned int type;
1605
0
    PACKET sni, tmppkt;
1606
0
    size_t ext_len;
1607
1608
0
    tmppkt = hello->extensions;
1609
1610
0
    if (!PACKET_forward(&tmppkt, 2)
1611
0
        || !PACKET_get_net_2(&tmppkt, &type)
1612
0
        || !PACKET_get_length_prefixed_2(&tmppkt, &sni)) {
1613
0
        return;
1614
0
    }
1615
1616
0
    if (type != TLSEXT_TYPE_server_name)
1617
0
        return;
1618
1619
0
    ext_len = TLS1_get_client_version(
1620
0
                  SSL_CONNECTION_GET_SSL(s))
1621
0
            >= TLS1_2_VERSION
1622
0
        ? sizeof(kSafariExtensionsBlock)
1623
0
        : kSafariCommonExtensionsLength;
1624
1625
0
    s->s3.is_probably_safari = PACKET_equal(&tmppkt, kSafariExtensionsBlock,
1626
0
        ext_len);
1627
0
}
1628
1629
#define RENEG_OPTIONS_OK(options)             \
1630
80
    ((options & SSL_OP_NO_RENEGOTIATION) == 0 \
1631
80
        && (options & SSL_OP_ALLOW_CLIENT_RENEGOTIATION) != 0)
1632
1633
MSG_PROCESS_RETURN tls_process_client_hello(SSL_CONNECTION *s, PACKET *pkt)
1634
5.24k
{
1635
    /* |cookie| will only be initialized for DTLS. */
1636
5.24k
    PACKET session_id, compression, extensions, cookie;
1637
5.24k
    CLIENTHELLO_MSG *clienthello = NULL;
1638
1639
5.24k
#ifndef OPENSSL_NO_ECH
1640
    /*
1641
     * For a split-mode backend we want to have a way to point at the CH octets
1642
     * for the accept-confirmation calculation. The split-mode backend does not
1643
     * need any ECH secrets, but it does need to see the inner CH and be the TLS
1644
     * endpoint with which the ECH encrypting client sets up the TLS session.
1645
     * The split-mode backend however does need to do an ECH confirm calculation
1646
     * so we need to tee that up. The result of that calculation will be put in
1647
     * the ServerHello.random (or ECH extension if HRR) to signal to the client
1648
     * that ECH "worked."
1649
     */
1650
5.24k
    if (s->server && PACKET_remaining(pkt) != 0) {
1651
5.22k
        int rv = 0, innerflag = OSSL_ECH_UNKNOWN_CH_TYPE;
1652
5.22k
        size_t startofsessid = 0, startofexts = 0, echoffset = 0;
1653
5.22k
        size_t outersnioffset = 0; /* offset to SNI in outer */
1654
5.22k
        uint16_t echtype = OSSL_ECH_type_unknown; /* type of ECH seen */
1655
5.22k
        const unsigned char *pbuf = NULL;
1656
1657
        /* reset needed in case of HRR */
1658
5.22k
        s->ext.ech.ch_offsets_done = 0;
1659
5.22k
        rv = ossl_ech_get_ch_offsets(s, pkt, &startofsessid, &startofexts,
1660
5.22k
            &echoffset, &echtype, &innerflag,
1661
5.22k
            &outersnioffset);
1662
5.22k
        if (rv != 1) {
1663
            /* SSLfatal already called */
1664
5
            goto err;
1665
5
        }
1666
5.22k
        if (innerflag == OSSL_ECH_INNER_CH_TYPE) {
1667
17
            WPACKET inner;
1668
1669
17
            OSSL_TRACE(TLS, "Got inner ECH so setting backend\n");
1670
            /* For backend, include msg type & 3 octet length */
1671
17
            s->ext.ech.backend = 1;
1672
17
            s->ext.ech.attempted_type = TLSEXT_TYPE_ech;
1673
17
            OPENSSL_free(s->ext.ech.innerch);
1674
17
            s->ext.ech.innerch_len = PACKET_remaining(pkt);
1675
17
            if (PACKET_peek_bytes(pkt, &pbuf, s->ext.ech.innerch_len) != 1) {
1676
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1677
0
                goto err;
1678
0
            }
1679
17
            s->ext.ech.innerch_len += SSL3_HM_HEADER_LENGTH; /* 4 */
1680
17
            s->ext.ech.innerch = OPENSSL_malloc(s->ext.ech.innerch_len);
1681
17
            if (s->ext.ech.innerch == NULL) {
1682
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1683
0
                goto err;
1684
0
            }
1685
17
            if (!WPACKET_init_static_len(&inner, s->ext.ech.innerch,
1686
17
                    s->ext.ech.innerch_len, 0)) {
1687
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1688
0
                goto err;
1689
0
            }
1690
17
            if (!WPACKET_put_bytes_u8(&inner, SSL3_MT_CLIENT_HELLO)
1691
17
                || !WPACKET_put_bytes_u24(&inner, s->ext.ech.innerch_len - SSL3_HM_HEADER_LENGTH)
1692
17
                || !WPACKET_memcpy(&inner, pbuf, s->ext.ech.innerch_len - SSL3_HM_HEADER_LENGTH)
1693
17
                || !WPACKET_finish(&inner)) {
1694
0
                WPACKET_cleanup(&inner);
1695
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1696
0
                goto err;
1697
0
            }
1698
17
            if (ossl_ech_intbuf_add(s, s->ext.ech.innerch,
1699
17
                    s->ext.ech.innerch_len, 0)
1700
17
                != 1) {
1701
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1702
0
                goto err;
1703
0
            }
1704
5.20k
        } else if (s->ext.ech.es != NULL) {
1705
0
            PACKET newpkt;
1706
0
            int secondtime = s->ext.ech.success;
1707
1708
            /*
1709
             * if ECH decrypt worked first time (success == 1) then fail
1710
             * if there's no ECH extension at all 2nd time
1711
             */
1712
0
            if (secondtime == 1 && echoffset == 0) {
1713
0
                SSLfatal(s, SSL_AD_MISSING_EXTENSION,
1714
0
                    SSL_R_TLSV13_ALERT_MISSING_EXTENSION);
1715
0
                goto err;
1716
0
            }
1717
0
            if (ossl_ech_early_decrypt(s, pkt, &newpkt) != 1) {
1718
                /* SSLfatal() already called */
1719
0
                goto err;
1720
0
            }
1721
0
            if (s->ext.ech.success == 1) {
1722
                /*
1723
                 * Replace the outer CH with the inner, as long as there's
1724
                 * space, which there better be! (a bug triggered a bigger
1725
                 * inner CH once;-)
1726
                 */
1727
0
                if (PACKET_remaining(&newpkt) > PACKET_remaining(pkt)) {
1728
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1729
0
                    goto err;
1730
0
                }
1731
0
                *pkt = newpkt;
1732
0
            } else if (secondtime == 1 && s->ext.ech.success == 0) {
1733
                /* 2nd time decrypt failed */
1734
0
                SSLfatal(s, SSL_AD_DECRYPT_ERROR, ERR_R_INTERNAL_ERROR);
1735
0
                goto err;
1736
0
            }
1737
0
        }
1738
5.22k
    }
1739
5.23k
#endif
1740
1741
    /* Check if this is actually an unexpected renegotiation ClientHello */
1742
5.23k
    if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1743
40
        if (!ossl_assert(!SSL_CONNECTION_IS_TLS13(s))) {
1744
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1745
0
            goto err;
1746
0
        }
1747
40
        if (!RENEG_OPTIONS_OK(s->options)
1748
0
            || (!s->s3.send_connection_binding
1749
0
                && (s->options
1750
0
                       & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)
1751
40
                    == 0)) {
1752
40
            ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1753
40
            return MSG_PROCESS_FINISHED_READING;
1754
40
        }
1755
0
        s->renegotiate = 1;
1756
0
        s->new_session = 1;
1757
0
    }
1758
1759
5.19k
    clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1760
5.19k
    if (clienthello == NULL) {
1761
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1762
0
        goto err;
1763
0
    }
1764
1765
    /*
1766
     * First, parse the raw ClientHello data into the CLIENTHELLO_MSG structure.
1767
     */
1768
5.19k
    PACKET_null_init(&cookie);
1769
1770
5.19k
    if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1771
11
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1772
11
        goto err;
1773
11
    }
1774
1775
5.18k
    if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1776
5.16k
        || !PACKET_get_length_prefixed_1(pkt, &session_id)
1777
5.15k
        || !PACKET_copy_all(&session_id, clienthello->session_id,
1778
5.15k
            SSL_MAX_SSL_SESSION_ID_LENGTH,
1779
5.15k
            &clienthello->session_id_len)) {
1780
62
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1781
62
        goto err;
1782
62
    }
1783
1784
5.12k
    if (SSL_CONNECTION_IS_DTLS(s)) {
1785
1.25k
        if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1786
2
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1787
2
            goto err;
1788
2
        }
1789
1.25k
        if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1790
1.25k
                DTLS1_COOKIE_LENGTH,
1791
1.25k
                &clienthello->dtls_cookie_len)) {
1792
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1793
0
            goto err;
1794
0
        }
1795
        /*
1796
         * If we require cookies and this ClientHello doesn't contain one,
1797
         * just return since we do not want to allocate any memory yet.
1798
         * So check cookie length...
1799
         */
1800
1.25k
        if (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE) {
1801
0
            if (clienthello->dtls_cookie_len == 0) {
1802
0
                OPENSSL_free(clienthello);
1803
0
                return MSG_PROCESS_FINISHED_READING;
1804
0
            }
1805
0
        }
1806
1.25k
    }
1807
1808
5.12k
    if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1809
61
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1810
61
        goto err;
1811
61
    }
1812
1813
5.06k
    if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1814
34
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1815
34
        goto err;
1816
34
    }
1817
1818
    /* Could be empty. */
1819
5.02k
    if (PACKET_remaining(pkt) == 0) {
1820
217
        PACKET_null_init(&clienthello->extensions);
1821
4.80k
    } else {
1822
4.80k
        if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1823
4.73k
            || PACKET_remaining(pkt) != 0) {
1824
128
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1825
128
            goto err;
1826
128
        }
1827
4.80k
    }
1828
1829
4.89k
    if (!PACKET_copy_all(&compression, clienthello->compressions,
1830
4.89k
            MAX_COMPRESSIONS_SIZE,
1831
4.89k
            &clienthello->compressions_len)) {
1832
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1833
0
        goto err;
1834
0
    }
1835
1836
    /* Preserve the raw extensions PACKET for later use */
1837
4.89k
    extensions = clienthello->extensions;
1838
4.89k
    if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1839
4.89k
            &clienthello->pre_proc_exts,
1840
4.89k
            &clienthello->pre_proc_exts_len, 1)) {
1841
        /* SSLfatal already been called */
1842
74
        goto err;
1843
74
    }
1844
4.82k
    s->clienthello = clienthello;
1845
1846
4.82k
    return MSG_PROCESS_CONTINUE_PROCESSING;
1847
1848
377
err:
1849
377
    if (clienthello != NULL)
1850
372
        OPENSSL_free(clienthello->pre_proc_exts);
1851
377
    OPENSSL_free(clienthello);
1852
377
#ifndef OPENSSL_NO_ECH
1853
377
    s->clienthello = NULL;
1854
377
    OPENSSL_free(s->ext.ech.innerch);
1855
377
    s->ext.ech.innerch = NULL;
1856
377
    s->ext.ech.innerch_len = 0;
1857
377
#endif
1858
1859
377
    return MSG_PROCESS_ERROR;
1860
4.89k
}
1861
1862
static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
1863
4.82k
{
1864
4.82k
    unsigned int j;
1865
4.82k
    int i, al = SSL_AD_INTERNAL_ERROR;
1866
4.82k
    int protverr;
1867
4.82k
    unsigned long id;
1868
4.82k
#ifndef OPENSSL_NO_COMP
1869
4.82k
    SSL_COMP *comp = NULL;
1870
4.82k
#endif
1871
4.82k
    const SSL_CIPHER *c;
1872
4.82k
    STACK_OF(SSL_CIPHER) *ciphers = NULL;
1873
4.82k
    STACK_OF(SSL_CIPHER) *scsvs = NULL;
1874
4.82k
    CLIENTHELLO_MSG *clienthello = s->clienthello;
1875
4.82k
    DOWNGRADE dgrd = DOWNGRADE_NONE;
1876
4.82k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1877
4.82k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1878
4.82k
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1879
1880
    /* Finished parsing the ClientHello, now we can start processing it */
1881
    /* Give the ClientHello callback a crack at things */
1882
4.82k
    if (sctx->client_hello_cb != NULL) {
1883
        /* A failure in the ClientHello callback terminates the connection. */
1884
0
        switch (sctx->client_hello_cb(ussl, &al, sctx->client_hello_cb_arg)) {
1885
0
        case SSL_CLIENT_HELLO_SUCCESS:
1886
0
            break;
1887
0
        case SSL_CLIENT_HELLO_RETRY:
1888
0
            s->rwstate = SSL_CLIENT_HELLO_CB;
1889
0
            return -1;
1890
0
        case SSL_CLIENT_HELLO_ERROR:
1891
0
        default:
1892
0
            SSLfatal(s, al, SSL_R_CALLBACK_FAILED);
1893
0
            goto err;
1894
0
        }
1895
0
    }
1896
1897
    /* Set up the client_random */
1898
4.82k
    memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);
1899
1900
    /* Choose the server SSL/TLS/DTLS version. */
1901
4.82k
    protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1902
1903
4.82k
#ifndef OPENSSL_NO_ECH
1904
4.82k
    if (protverr && s->ext.ech.success == 1) {
1905
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, protverr);
1906
0
    }
1907
4.82k
#endif
1908
4.82k
    if (protverr) {
1909
99
        if (SSL_IS_FIRST_HANDSHAKE(s)) {
1910
            /* like ssl3_get_record, send alert using remote version number */
1911
99
            s->version = s->client_version = clienthello->legacy_version;
1912
99
        }
1913
99
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);
1914
99
        goto err;
1915
99
    }
1916
1917
    /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1918
4.72k
    if (SSL_CONNECTION_IS_TLS13(s)
1919
854
        && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1920
2
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
1921
2
        goto err;
1922
2
    }
1923
1924
4.72k
    if (SSL_CONNECTION_IS_DTLS(s)) {
1925
        /* Empty cookie was already handled above by returning early. */
1926
1.13k
        if (SSL_get_options(ssl) & SSL_OP_COOKIE_EXCHANGE) {
1927
0
            if (sctx->app_verify_cookie_cb != NULL) {
1928
0
                if (sctx->app_verify_cookie_cb(ussl, clienthello->dtls_cookie,
1929
0
                        (unsigned int)clienthello->dtls_cookie_len)
1930
0
                    == 0) {
1931
0
                    SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1932
0
                        SSL_R_COOKIE_MISMATCH);
1933
0
                    goto err;
1934
                    /* else cookie verification succeeded */
1935
0
                }
1936
                /* default verification */
1937
0
            } else if (s->d1->cookie_len != clienthello->dtls_cookie_len
1938
0
                || memcmp(clienthello->dtls_cookie, s->d1->cookie,
1939
0
                       s->d1->cookie_len)
1940
0
                    != 0) {
1941
0
                SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_COOKIE_MISMATCH);
1942
0
                goto err;
1943
0
            }
1944
0
            s->d1->cookie_verified = 1;
1945
0
        }
1946
1.13k
    }
1947
1948
4.72k
    s->hit = 0;
1949
1950
4.72k
    if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites)
1951
4.71k
        || !ossl_bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers, &scsvs, 1)) {
1952
        /* SSLfatal() already called */
1953
6
        goto err;
1954
6
    }
1955
1956
4.71k
    s->s3.send_connection_binding = 0;
1957
    /* Check what signalling cipher-suite values were received. */
1958
4.71k
    if (scsvs != NULL) {
1959
6.81k
        for (i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1960
2.10k
            c = sk_SSL_CIPHER_value(scsvs, i);
1961
2.10k
            if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1962
1.99k
                if (s->renegotiate) {
1963
                    /* SCSV is fatal if renegotiating */
1964
0
                    SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
1965
0
                        SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
1966
0
                    goto err;
1967
0
                }
1968
1.99k
                s->s3.send_connection_binding = 1;
1969
1.99k
            } else if (SSL_CIPHER_get_id(c) == SSL3_CK_FALLBACK_SCSV && !ssl_check_version_downgrade(s)) {
1970
                /*
1971
                 * This SCSV indicates that the client previously tried
1972
                 * a higher version.  We should fail if the current version
1973
                 * is an unexpected downgrade, as that indicates that the first
1974
                 * connection may have been tampered with in order to trigger
1975
                 * an insecure downgrade.
1976
                 */
1977
4
                SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
1978
4
                    SSL_R_INAPPROPRIATE_FALLBACK);
1979
4
                goto err;
1980
4
            }
1981
2.10k
        }
1982
4.71k
    }
1983
1984
    /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1985
4.71k
    if (SSL_CONNECTION_IS_TLS13(s)) {
1986
852
        const SSL_CIPHER *cipher = ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(ssl));
1987
1988
852
        if (cipher == NULL) {
1989
7
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
1990
7
            goto err;
1991
7
        }
1992
845
        if (s->hello_retry_request == SSL_HRR_PENDING
1993
35
            && (s->s3.tmp.new_cipher == NULL
1994
35
                || s->s3.tmp.new_cipher->id != cipher->id)) {
1995
            /*
1996
             * A previous HRR picked a different ciphersuite to the one we
1997
             * just selected. Something must have changed.
1998
             */
1999
1
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);
2000
1
            goto err;
2001
1
        }
2002
844
        s->s3.tmp.new_cipher = cipher;
2003
844
    }
2004
2005
    /* We need to do this before getting the session */
2006
4.70k
    if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
2007
4.70k
            SSL_EXT_CLIENT_HELLO,
2008
4.70k
            clienthello->pre_proc_exts, NULL, 0)) {
2009
        /* SSLfatal() already called */
2010
3
        goto err;
2011
3
    }
2012
2013
    /*
2014
     * We don't allow resumption in a backwards compatible ClientHello.
2015
     * In TLS1.1+, session_id MUST be empty.
2016
     *
2017
     * Versions before 0.9.7 always allow clients to resume sessions in
2018
     * renegotiation. 0.9.7 and later allow this by default, but optionally
2019
     * ignore resumption requests with flag
2020
     * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
2021
     * than a change to default behavior so that applications relying on
2022
     * this for security won't even compile against older library versions).
2023
     * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
2024
     * request renegotiation but not a new session (s->new_session remains
2025
     * unset): for servers, this essentially just means that the
2026
     * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
2027
     * ignored.
2028
     */
2029
4.70k
    if (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)) {
2030
0
        if (!ssl_get_new_session(s, 1)) {
2031
            /* SSLfatal() already called */
2032
0
            goto err;
2033
0
        }
2034
4.70k
    } else {
2035
4.70k
        i = ssl_get_prev_session(s, clienthello);
2036
4.70k
        if (i == 1) {
2037
            /* previous session */
2038
49
            s->hit = 1;
2039
4.65k
        } else if (i == -1) {
2040
            /* SSLfatal() already called */
2041
100
            goto err;
2042
4.55k
        } else {
2043
            /* i == 0 */
2044
4.55k
            if (!ssl_get_new_session(s, 1)) {
2045
                /* SSLfatal() already called */
2046
0
                goto err;
2047
0
            }
2048
4.55k
        }
2049
4.70k
    }
2050
2051
4.60k
    if (SSL_CONNECTION_IS_TLS13(s)) {
2052
746
        memcpy(s->tmp_session_id, s->clienthello->session_id,
2053
746
            s->clienthello->session_id_len);
2054
746
        s->tmp_session_id_len = s->clienthello->session_id_len;
2055
746
    }
2056
2057
    /*
2058
     * If it is a hit, check that the cipher is in the list. In TLSv1.3 we check
2059
     * ciphersuite compatibility with the session as part of resumption.
2060
     */
2061
4.60k
    if (!SSL_CONNECTION_IS_TLS13(s) && s->hit) {
2062
49
        j = 0;
2063
49
        id = s->session->cipher->id;
2064
2065
49
        OSSL_TRACE_BEGIN(TLS_CIPHER)
2066
0
        {
2067
0
            BIO_printf(trc_out, "client sent %d ciphers\n",
2068
0
                sk_SSL_CIPHER_num(ciphers));
2069
0
        }
2070
329
        for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
2071
318
            c = sk_SSL_CIPHER_value(ciphers, i);
2072
318
            if (trc_out != NULL)
2073
0
                BIO_printf(trc_out, "client [%2d of %2d]:%s\n", i,
2074
0
                    sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
2075
318
            if (c->id == id) {
2076
38
                j = 1;
2077
38
                break;
2078
38
            }
2079
318
        }
2080
49
        if (j == 0) {
2081
            /*
2082
             * we need to have the cipher in the cipher list if we are asked
2083
             * to reuse it
2084
             */
2085
11
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2086
11
                SSL_R_REQUIRED_CIPHER_MISSING);
2087
11
            OSSL_TRACE_CANCEL(TLS_CIPHER);
2088
11
            goto err;
2089
11
        }
2090
49
        OSSL_TRACE_END(TLS_CIPHER);
2091
49
    }
2092
2093
    /* At least one compression method must be preset. */
2094
4.59k
    if (clienthello->compressions_len == 0) {
2095
26
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_COMPRESSION_SPECIFIED);
2096
26
        goto err;
2097
26
    }
2098
    /* Make sure at least the null compression is supported. */
2099
4.56k
    if (memchr(clienthello->compressions, 0,
2100
4.56k
            clienthello->compressions_len)
2101
4.56k
        == NULL) {
2102
16
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2103
16
            SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
2104
16
        goto err;
2105
16
    }
2106
2107
4.54k
    if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
2108
0
        ssl_check_for_safari(s, clienthello);
2109
2110
    /* TLS extensions */
2111
4.54k
    if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
2112
4.54k
            clienthello->pre_proc_exts, NULL, 0, 1)) {
2113
        /* SSLfatal() already called */
2114
1.05k
        goto err;
2115
1.05k
    }
2116
2117
    /*
2118
     * Check if we want to use external pre-shared secret for this handshake
2119
     * for not reused session only. We need to generate server_random before
2120
     * calling tls_session_secret_cb in order to allow SessionTicket
2121
     * processing to use it in key derivation.
2122
     */
2123
3.49k
    {
2124
3.49k
        unsigned char *pos;
2125
3.49k
        pos = s->s3.server_random;
2126
3.49k
        if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE, dgrd) <= 0) {
2127
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2128
0
            goto err;
2129
0
        }
2130
3.49k
    }
2131
2132
3.49k
    if (!s->hit && !tls1_set_server_sigalgs(s)) {
2133
        /* SSLfatal() already called */
2134
29
        goto err;
2135
29
    }
2136
2137
    /*
2138
     * Unless ECH has worked or not been configured we won't call
2139
     * the session_secret_cb now because we'll need to calculate the
2140
     * server random later to include the ECH accept value.
2141
     * We can't do it now as we don't yet have the SH encoding.
2142
     */
2143
3.46k
    if (
2144
3.46k
#ifndef OPENSSL_NO_ECH
2145
3.46k
        ((s->ext.ech.es != NULL && s->ext.ech.success == 1)
2146
3.46k
            || s->ext.ech.es == NULL)
2147
3.46k
        &&
2148
3.46k
#endif
2149
3.46k
        !s->hit
2150
3.43k
        && s->version >= TLS1_VERSION
2151
3.43k
        && !SSL_CONNECTION_IS_TLS13(s)
2152
2.85k
        && !SSL_CONNECTION_IS_DTLS(s)
2153
2.03k
        && s->ext.session_secret_cb != NULL) {
2154
0
        const SSL_CIPHER *pref_cipher = NULL;
2155
2156
        /*
2157
         * s->session->master_key_length is a size_t, but this is an int for
2158
         * backwards compat reasons
2159
         */
2160
0
        int master_key_length;
2161
2162
0
        master_key_length = sizeof(s->session->master_key);
2163
0
        if (s->ext.session_secret_cb(ussl, s->session->master_key,
2164
0
                &master_key_length, ciphers,
2165
0
                &pref_cipher,
2166
0
                s->ext.session_secret_cb_arg)
2167
0
            && master_key_length > 0) {
2168
0
            s->session->master_key_length = master_key_length;
2169
0
            s->hit = 1;
2170
0
            s->peer_ciphers = ciphers;
2171
0
            s->session->verify_result = X509_V_OK;
2172
2173
            /*
2174
             * Per RFC 4851, Section 3.2.2:
2175
             * If the ClientHello contains both a Session ID and a PAC-Opaque in
2176
             * the SessionTicket extension, and the server resumes the session
2177
             * using the PAC-Opaque, it should echo the same Session ID in the
2178
             * ServerHello.
2179
             */
2180
0
            if (clienthello->session_id_len > 0) {
2181
0
                memcpy(s->session->session_id, clienthello->session_id,
2182
0
                    clienthello->session_id_len);
2183
0
                s->session->session_id_length = clienthello->session_id_len;
2184
0
            }
2185
2186
0
            ciphers = NULL;
2187
2188
            /* check if some cipher was preferred by call back */
2189
0
            if (pref_cipher == NULL)
2190
0
                pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2191
0
                    SSL_get_ciphers(ssl));
2192
0
            if (pref_cipher == NULL) {
2193
0
                SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
2194
0
                goto err;
2195
0
            }
2196
2197
0
            s->session->cipher = pref_cipher;
2198
0
            sk_SSL_CIPHER_free(s->cipher_list);
2199
0
            s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);
2200
0
            sk_SSL_CIPHER_free(s->cipher_list_by_id);
2201
0
            s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);
2202
0
        }
2203
0
    }
2204
2205
    /*
2206
     * Worst case, we will use the NULL compression, but if we have other
2207
     * options, we will now look for them.  We have complen-1 compression
2208
     * algorithms from the client, starting at q.
2209
     */
2210
3.46k
    s->s3.tmp.new_compression = NULL;
2211
3.46k
    if (SSL_CONNECTION_IS_TLS13(s)) {
2212
        /*
2213
         * We already checked above that the NULL compression method appears in
2214
         * the list. Now we check there aren't any others (which is illegal in
2215
         * a TLSv1.3 ClientHello.
2216
         */
2217
579
        if (clienthello->compressions_len != 1) {
2218
1
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2219
1
                SSL_R_INVALID_COMPRESSION_ALGORITHM);
2220
1
            goto err;
2221
1
        }
2222
579
    }
2223
2.88k
#ifndef OPENSSL_NO_COMP
2224
    /* This only happens if we have a cache hit */
2225
2.88k
    else if (s->session->compress_meth != 0) {
2226
0
        int m, comp_id = s->session->compress_meth;
2227
0
        unsigned int k;
2228
        /* Perform sanity checks on resumed compression algorithm */
2229
        /* Can't disable compression */
2230
0
        if (!ssl_allow_compression(s)) {
2231
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2232
0
                SSL_R_INCONSISTENT_COMPRESSION);
2233
0
            goto err;
2234
0
        }
2235
        /* Look for resumed compression method */
2236
0
        for (m = 0; m < sk_SSL_COMP_num(sctx->comp_methods); m++) {
2237
0
            comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2238
0
            if (comp_id == comp->id) {
2239
0
                s->s3.tmp.new_compression = comp;
2240
0
                break;
2241
0
            }
2242
0
        }
2243
0
        if (s->s3.tmp.new_compression == NULL) {
2244
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2245
0
                SSL_R_INVALID_COMPRESSION_ALGORITHM);
2246
0
            goto err;
2247
0
        }
2248
        /* Look for resumed method in compression list */
2249
0
        for (k = 0; k < clienthello->compressions_len; k++) {
2250
0
            if (clienthello->compressions[k] == comp_id)
2251
0
                break;
2252
0
        }
2253
0
        if (k >= clienthello->compressions_len) {
2254
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2255
0
                SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
2256
0
            goto err;
2257
0
        }
2258
2.88k
    } else if (s->hit) {
2259
33
        comp = NULL;
2260
2.85k
    } else if (ssl_allow_compression(s) && sctx->comp_methods) {
2261
        /* See if we have a match */
2262
0
        int m, nn, v, done = 0;
2263
0
        unsigned int o;
2264
2265
0
        nn = sk_SSL_COMP_num(sctx->comp_methods);
2266
0
        for (m = 0; m < nn; m++) {
2267
0
            comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2268
0
            v = comp->id;
2269
0
            for (o = 0; o < clienthello->compressions_len; o++) {
2270
0
                if (v == clienthello->compressions[o]) {
2271
0
                    done = 1;
2272
0
                    break;
2273
0
                }
2274
0
            }
2275
0
            if (done)
2276
0
                break;
2277
0
        }
2278
0
        if (done)
2279
0
            s->s3.tmp.new_compression = comp;
2280
0
        else
2281
0
            comp = NULL;
2282
0
    }
2283
#else
2284
    /*
2285
     * If compression is disabled we'd better not try to resume a session
2286
     * using compression.
2287
     */
2288
    if (s->session->compress_meth != 0) {
2289
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
2290
        goto err;
2291
    }
2292
#endif
2293
2294
    /*
2295
     * Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher
2296
     */
2297
2298
3.46k
    if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2299
3.42k
        sk_SSL_CIPHER_free(s->peer_ciphers);
2300
3.42k
        s->peer_ciphers = ciphers;
2301
3.42k
        if (ciphers == NULL) {
2302
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2303
0
            goto err;
2304
0
        }
2305
3.42k
        ciphers = NULL;
2306
3.42k
    }
2307
2308
3.46k
    if (!s->hit) {
2309
#ifdef OPENSSL_NO_COMP
2310
        s->session->compress_meth = 0;
2311
#else
2312
3.42k
        s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
2313
3.42k
#endif
2314
3.42k
    }
2315
2316
3.46k
    sk_SSL_CIPHER_free(ciphers);
2317
3.46k
    sk_SSL_CIPHER_free(scsvs);
2318
3.46k
    OPENSSL_free(clienthello->pre_proc_exts);
2319
3.46k
    OPENSSL_free(s->clienthello);
2320
3.46k
    s->clienthello = NULL;
2321
3.46k
    return 1;
2322
1.36k
err:
2323
1.36k
    sk_SSL_CIPHER_free(ciphers);
2324
1.36k
    sk_SSL_CIPHER_free(scsvs);
2325
1.36k
    if (clienthello != NULL)
2326
1.36k
        OPENSSL_free(clienthello->pre_proc_exts);
2327
1.36k
    OPENSSL_free(s->clienthello);
2328
1.36k
    s->clienthello = NULL;
2329
2330
1.36k
    return 0;
2331
3.46k
}
2332
2333
/*
2334
 * Call the status request callback if needed. Upon success, returns 1.
2335
 * Upon failure, returns 0.
2336
 */
2337
static int tls_handle_status_request(SSL_CONNECTION *s)
2338
13.6k
{
2339
13.6k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2340
2341
13.6k
    s->ext.status_expected = 0;
2342
2343
    /*
2344
     * If status request then ask callback what to do. Note: this must be
2345
     * called after servername callbacks in case the certificate has changed,
2346
     * and must be called after the cipher has been chosen because this may
2347
     * influence which certificate is sent
2348
     */
2349
13.6k
    if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && sctx != NULL
2350
1.03k
        && sctx->ext.status_cb != NULL) {
2351
0
        int ret;
2352
2353
        /* If no certificate can't return certificate status */
2354
0
        if (s->s3.tmp.cert != NULL) {
2355
            /*
2356
             * Set current certificate to one we will use so SSL_get_certificate
2357
             * et al can pick it up.
2358
             */
2359
0
            s->cert->key = s->s3.tmp.cert;
2360
0
            ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),
2361
0
                sctx->ext.status_arg);
2362
0
            switch (ret) {
2363
                /* We don't want to send a status request response */
2364
0
            case SSL_TLSEXT_ERR_NOACK:
2365
0
                s->ext.status_expected = 0;
2366
0
                break;
2367
                /* status request response should be sent */
2368
0
            case SSL_TLSEXT_ERR_OK:
2369
0
#ifndef OPENSSL_NO_OCSP
2370
0
                if (s->ext.ocsp.resp_ex != NULL
2371
0
                    && sk_OCSP_RESPONSE_num(s->ext.ocsp.resp_ex) > 0)
2372
0
                    s->ext.status_expected = 1;
2373
0
#endif
2374
0
                break;
2375
                /* something bad happened */
2376
0
            case SSL_TLSEXT_ERR_ALERT_FATAL:
2377
0
            default:
2378
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);
2379
0
                return 0;
2380
0
            }
2381
0
        }
2382
0
    }
2383
2384
13.6k
    return 1;
2385
13.6k
}
2386
2387
/*
2388
 * Call the alpn_select callback if needed. Upon success, returns 1.
2389
 * Upon failure, returns 0.
2390
 */
2391
int tls_handle_alpn(SSL_CONNECTION *s)
2392
23.7k
{
2393
23.7k
    const unsigned char *selected = NULL;
2394
23.7k
    unsigned char selected_len = 0;
2395
23.7k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2396
2397
23.7k
    if (sctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
2398
0
        int r = sctx->ext.alpn_select_cb(SSL_CONNECTION_GET_USER_SSL(s),
2399
0
            &selected, &selected_len,
2400
0
            s->s3.alpn_proposed,
2401
0
            (unsigned int)s->s3.alpn_proposed_len,
2402
0
            sctx->ext.alpn_select_cb_arg);
2403
2404
0
        if (r == SSL_TLSEXT_ERR_OK) {
2405
0
            OPENSSL_free(s->s3.alpn_selected);
2406
0
            s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
2407
0
            if (s->s3.alpn_selected == NULL) {
2408
0
                s->s3.alpn_selected_len = 0;
2409
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2410
0
                return 0;
2411
0
            }
2412
0
            s->s3.alpn_selected_len = selected_len;
2413
0
#ifndef OPENSSL_NO_NEXTPROTONEG
2414
            /* ALPN takes precedence over NPN. */
2415
0
            s->s3.npn_seen = 0;
2416
0
#endif
2417
2418
            /* Check ALPN is consistent with session */
2419
0
            if (s->session->ext.alpn_selected == NULL
2420
0
                || selected_len != s->session->ext.alpn_selected_len
2421
0
                || memcmp(selected, s->session->ext.alpn_selected,
2422
0
                       selected_len)
2423
0
                    != 0) {
2424
                /* Not consistent so can't be used for early_data */
2425
0
                s->ext.early_data_ok = 0;
2426
2427
0
                if (!s->hit) {
2428
                    /*
2429
                     * This is a new session and so alpn_selected should have
2430
                     * been initialised to NULL. We should update it with the
2431
                     * selected ALPN.
2432
                     */
2433
0
                    if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2434
0
                        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2435
0
                            ERR_R_INTERNAL_ERROR);
2436
0
                        return 0;
2437
0
                    }
2438
0
                    s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2439
0
                        selected_len);
2440
0
                    if (s->session->ext.alpn_selected == NULL) {
2441
0
                        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2442
0
                            ERR_R_INTERNAL_ERROR);
2443
0
                        return 0;
2444
0
                    }
2445
0
                    s->session->ext.alpn_selected_len = selected_len;
2446
0
                }
2447
0
            }
2448
2449
0
            return 1;
2450
0
        } else if (r != SSL_TLSEXT_ERR_NOACK) {
2451
0
            SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,
2452
0
                SSL_R_NO_APPLICATION_PROTOCOL);
2453
0
            return 0;
2454
0
        }
2455
        /*
2456
         * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2457
         * present.
2458
         */
2459
0
    }
2460
2461
    /* Check ALPN is consistent with session */
2462
23.7k
    if (s->session->ext.alpn_selected != NULL) {
2463
        /* Not consistent so can't be used for early_data */
2464
0
        s->ext.early_data_ok = 0;
2465
0
    }
2466
2467
23.7k
    return 1;
2468
23.7k
}
2469
2470
WORK_STATE tls_post_process_client_hello(SSL_CONNECTION *s, WORK_STATE wst)
2471
25.5k
{
2472
25.5k
    const SSL_CIPHER *cipher;
2473
25.5k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2474
25.5k
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
2475
2476
25.5k
    if (wst == WORK_MORE_A) {
2477
25.5k
        int rv = tls_early_post_process_client_hello(s);
2478
2479
25.5k
        if (rv == 0) {
2480
            /* SSLfatal() was already called */
2481
5.98k
            goto err;
2482
5.98k
        }
2483
19.5k
        if (rv < 0)
2484
0
            return WORK_MORE_A;
2485
19.5k
        wst = WORK_MORE_B;
2486
19.5k
    }
2487
19.5k
    if (wst == WORK_MORE_B) {
2488
19.5k
        if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2489
            /* Let cert callback update server certificates if required */
2490
19.4k
            if (!s->hit && s->cert->cert_cb != NULL) {
2491
0
                int rv = s->cert->cert_cb(ussl, s->cert->cert_cb_arg);
2492
2493
0
                if (rv == 0) {
2494
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);
2495
0
                    goto err;
2496
0
                }
2497
0
                if (rv < 0) {
2498
0
                    s->rwstate = SSL_X509_LOOKUP;
2499
0
                    return WORK_MORE_B;
2500
0
                }
2501
0
                s->rwstate = SSL_NOTHING;
2502
0
            }
2503
2504
            /* In TLSv1.3 we selected the ciphersuite before resumption */
2505
19.4k
            if (!SSL_CONNECTION_IS_TLS13(s)) {
2506
17.0k
                cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2507
17.0k
                    SSL_get_ciphers(ssl));
2508
2509
17.0k
                if (cipher == NULL) {
2510
916
                    SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2511
916
                        SSL_R_NO_SHARED_CIPHER);
2512
916
                    goto err;
2513
916
                }
2514
16.1k
                s->s3.tmp.new_cipher = cipher;
2515
16.1k
            }
2516
18.4k
            if (!s->hit) {
2517
18.4k
                if (!tls_choose_sigalg(s, 1)) {
2518
                    /* SSLfatal already called */
2519
816
                    goto err;
2520
816
                }
2521
                /* check whether we should disable session resumption */
2522
17.6k
                if (s->not_resumable_session_cb != NULL)
2523
0
                    s->session->not_resumable = s->not_resumable_session_cb(ussl,
2524
0
                        ((s->s3.tmp.new_cipher->algorithm_mkey
2525
0
                             & (SSL_kDHE | SSL_kECDHE))
2526
0
                            != 0));
2527
17.6k
                if (s->session->not_resumable)
2528
                    /* do not send a session ticket */
2529
0
                    s->ext.ticket_expected = 0;
2530
17.6k
            }
2531
18.4k
        } else {
2532
            /* Session-id reuse */
2533
129
            s->s3.tmp.new_cipher = s->session->cipher;
2534
129
        }
2535
2536
        /*-
2537
         * we now have the following setup.
2538
         * client_random
2539
         * cipher_list          - our preferred list of ciphers
2540
         * ciphers              - the client's preferred list of ciphers
2541
         * compression          - basically ignored right now
2542
         * ssl version is set   - sslv3
2543
         * s->session           - The ssl session has been setup.
2544
         * s->hit               - session reuse flag
2545
         * s->s3.tmp.new_cipher - the new cipher to use.
2546
         */
2547
2548
        /*
2549
         * Call status_request callback if needed. Has to be done after the
2550
         * certificate callbacks etc above.
2551
         */
2552
17.7k
        if (!tls_handle_status_request(s)) {
2553
            /* SSLfatal() already called */
2554
0
            goto err;
2555
0
        }
2556
        /*
2557
         * Call alpn_select callback if needed.  Has to be done after SNI and
2558
         * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2559
         * we already did this because cipher negotiation happens earlier, and
2560
         * we must handle ALPN before we decide whether to accept early_data.
2561
         */
2562
17.7k
        if (!SSL_CONNECTION_IS_TLS13(s) && !tls_handle_alpn(s)) {
2563
            /* SSLfatal() already called */
2564
0
            goto err;
2565
0
        }
2566
2567
17.7k
        wst = WORK_MORE_C;
2568
17.7k
    }
2569
17.7k
#ifndef OPENSSL_NO_SRP
2570
17.7k
    if (wst == WORK_MORE_C) {
2571
17.7k
        int ret;
2572
17.7k
        if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2573
            /*
2574
             * callback indicates further work to be done
2575
             */
2576
0
            s->rwstate = SSL_X509_LOOKUP;
2577
0
            return WORK_MORE_C;
2578
0
        }
2579
17.7k
        if (ret < 0) {
2580
            /* SSLfatal() already called */
2581
0
            goto err;
2582
0
        }
2583
17.7k
    }
2584
17.7k
#endif
2585
2586
17.7k
    return WORK_FINISHED_STOP;
2587
7.72k
err:
2588
7.72k
    return WORK_ERROR;
2589
17.7k
}
2590
2591
CON_FUNC_RETURN tls_construct_server_hello(SSL_CONNECTION *s, WPACKET *pkt)
2592
3.15k
{
2593
3.15k
    int compm;
2594
3.15k
    size_t sl, len;
2595
3.15k
    int version;
2596
3.15k
    unsigned char *session_id;
2597
3.15k
    int usetls13 = SSL_CONNECTION_IS_TLS13(s)
2598
2.59k
        || s->hello_retry_request == SSL_HRR_PENDING;
2599
2600
3.15k
    version = usetls13 ? TLS1_2_VERSION : s->version;
2601
3.15k
    if (!WPACKET_put_bytes_u16(pkt, version)
2602
        /*
2603
         * Random stuff. Filling of the server_random takes place in
2604
         * tls_process_client_hello()
2605
         */
2606
3.15k
        || !WPACKET_memcpy(pkt,
2607
3.15k
            s->hello_retry_request == SSL_HRR_PENDING
2608
3.15k
                ? hrrrandom
2609
3.15k
                : s->s3.server_random,
2610
3.15k
            SSL3_RANDOM_SIZE)) {
2611
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2612
0
        return CON_FUNC_ERROR;
2613
0
    }
2614
2615
    /*-
2616
     * There are several cases for the session ID to send
2617
     * back in the server hello:
2618
     * - For session reuse from the session cache,
2619
     *   we send back the old session ID.
2620
     * - If stateless session reuse (using a session ticket)
2621
     *   is successful, we send back the client's "session ID"
2622
     *   (which doesn't actually identify the session).
2623
     * - If it is a new session, we send back the new
2624
     *   session ID.
2625
     * - However, if we want the new session to be single-use,
2626
     *   we send back a 0-length session ID.
2627
     * - In TLSv1.3 we echo back the session id sent to us by the client
2628
     *   regardless
2629
     * s->hit is non-zero in either case of session reuse,
2630
     * so the following won't overwrite an ID that we're supposed
2631
     * to send back.
2632
     */
2633
3.15k
    if (!(SSL_CONNECTION_GET_CTX(s)->session_cache_mode & SSL_SESS_CACHE_SERVER)
2634
0
        && !s->hit)
2635
0
        s->session->session_id_length = 0;
2636
2637
3.15k
    if (usetls13) {
2638
558
        sl = s->tmp_session_id_len;
2639
558
        session_id = s->tmp_session_id;
2640
2.59k
    } else {
2641
2.59k
        sl = s->session->session_id_length;
2642
2.59k
        session_id = s->session->session_id;
2643
2.59k
    }
2644
2645
3.15k
    if (sl > sizeof(s->session->session_id)) {
2646
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2647
0
        return CON_FUNC_ERROR;
2648
0
    }
2649
2650
    /* set up the compression method */
2651
#ifdef OPENSSL_NO_COMP
2652
    compm = 0;
2653
#else
2654
3.15k
    if (usetls13 || s->s3.tmp.new_compression == NULL)
2655
3.15k
        compm = 0;
2656
0
    else
2657
0
        compm = s->s3.tmp.new_compression->id;
2658
3.15k
#endif
2659
2660
3.15k
    if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2661
3.15k
        || !SSL_CONNECTION_GET_SSL(s)->method->put_cipher_by_char(s->s3.tmp.new_cipher,
2662
3.15k
            pkt, &len)
2663
3.15k
        || !WPACKET_put_bytes_u8(pkt, compm)) {
2664
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2665
0
        return CON_FUNC_ERROR;
2666
0
    }
2667
2668
3.15k
    if (!tls_construct_extensions(s, pkt,
2669
3.15k
            s->hello_retry_request == SSL_HRR_PENDING
2670
3.15k
                ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2671
3.15k
                : (SSL_CONNECTION_IS_TLS13(s)
2672
3.04k
                          ? SSL_EXT_TLS1_3_SERVER_HELLO
2673
3.04k
                          : SSL_EXT_TLS1_2_SERVER_HELLO),
2674
3.15k
            NULL, 0)) {
2675
        /* SSLfatal() already called */
2676
2
        return CON_FUNC_ERROR;
2677
2
    }
2678
2679
3.15k
    if (s->hello_retry_request == SSL_HRR_PENDING) {
2680
        /* Ditch the session. We'll create a new one next time around */
2681
116
        SSL_SESSION_free(s->session);
2682
116
        s->session = NULL;
2683
116
        s->hit = 0;
2684
2685
        /*
2686
         * Re-initialise the Transcript Hash. We're going to prepopulate it with
2687
         * a synthetic message_hash in place of ClientHello1.
2688
         */
2689
116
#ifndef OPENSSL_NO_ECH
2690
        /*
2691
         * if we're sending 2nd SH after HRR and we did ECH
2692
         * then we want to inject the hash of the inner CH1
2693
         * and not the outer (which is the default)
2694
         */
2695
116
        OSSL_TRACE_BEGIN(TLS)
2696
0
        {
2697
0
            BIO_printf(trc_out, "Checking success (%d)/innerCH (%p)\n",
2698
0
                s->ext.ech.success, (void *)s->ext.ech.innerch);
2699
0
        }
2700
116
        OSSL_TRACE_END(TLS);
2701
116
        if ((s->ext.ech.backend == 1 || s->ext.ech.success == 1)
2702
0
            && s->ext.ech.innerch != NULL) {
2703
            /* do pre-existing HRR stuff */
2704
0
            unsigned char hashval[EVP_MAX_MD_SIZE];
2705
0
            unsigned int hashlen;
2706
0
            EVP_MD_CTX *ctx = EVP_MD_CTX_new();
2707
0
            const EVP_MD *md = NULL;
2708
2709
0
            OSSL_TRACE(TLS, "Adding in digest of ClientHello\n");
2710
0
#ifdef OSSL_ECH_SUPERVERBOSE
2711
0
            ossl_ech_pbuf("innerch", s->ext.ech.innerch,
2712
0
                s->ext.ech.innerch_len);
2713
0
#endif
2714
0
            if (ctx == NULL) {
2715
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2716
0
                return CON_FUNC_ERROR;
2717
0
            }
2718
0
            md = ssl_handshake_md(s);
2719
0
            if (md == NULL) {
2720
0
                EVP_MD_CTX_free(ctx);
2721
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2722
0
                return CON_FUNC_ERROR;
2723
0
            }
2724
0
            if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
2725
0
                || EVP_DigestUpdate(ctx, s->ext.ech.innerch,
2726
0
                       s->ext.ech.innerch_len)
2727
0
                    <= 0
2728
0
                || EVP_DigestFinal_ex(ctx, hashval, &hashlen) <= 0) {
2729
0
                EVP_MD_CTX_free(ctx);
2730
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2731
0
                return CON_FUNC_ERROR;
2732
0
            }
2733
0
#ifdef OSSL_ECH_SUPERVERBOSE
2734
0
            ossl_ech_pbuf("digested CH", hashval, hashlen);
2735
0
#endif
2736
0
            EVP_MD_CTX_free(ctx);
2737
0
            if (ossl_ech_reset_hs_buffer(s, NULL, 0) != 1) {
2738
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2739
0
                return CON_FUNC_ERROR;
2740
0
            }
2741
0
            if (!create_synthetic_message_hash(s, hashval, hashlen, NULL, 0)) {
2742
                /* SSLfatal() already called */
2743
0
                return CON_FUNC_ERROR;
2744
0
            }
2745
116
        } else {
2746
116
            if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0))
2747
0
                return CON_FUNC_ERROR; /* SSLfatal() already called */
2748
116
        }
2749
#else
2750
        if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0))
2751
            /* SSLfatal() already called */
2752
            return CON_FUNC_ERROR;
2753
#endif /* OPENSSL_NO_ECH */
2754
3.03k
    } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2755
3.03k
        && !ssl3_digest_cached_records(s, 0)) {
2756
0
        /* SSLfatal() already called */;
2757
0
        return CON_FUNC_ERROR;
2758
0
    }
2759
2760
3.15k
#ifndef OPENSSL_NO_ECH
2761
    /*
2762
     * Calculate the ECH-accept server random to indicate that
2763
     * we're accepting ECH, if that's the case
2764
     */
2765
3.15k
    if (s->ext.ech.attempted_type == TLSEXT_TYPE_ech
2766
11
        && (s->ext.ech.backend == 1
2767
11
            || (s->ext.ech.es != NULL && s->ext.ech.success == 1))) {
2768
11
        unsigned char acbuf[8];
2769
11
        unsigned char *shbuf = NULL;
2770
11
        size_t shlen = 0;
2771
11
        size_t shoffset = 0;
2772
11
        int hrr = 0;
2773
2774
11
        if (s->hello_retry_request == SSL_HRR_PENDING)
2775
0
            hrr = 1;
2776
11
        memset(acbuf, 0, 8);
2777
11
        if (WPACKET_get_total_written(pkt, &shlen) != 1) {
2778
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2779
0
            return CON_FUNC_ERROR;
2780
0
        }
2781
11
        shbuf = WPACKET_get_curr(pkt) - shlen;
2782
        /* we need to fixup SH length here */
2783
11
        shbuf[1] = ((shlen - 4)) >> 16 & 0xff;
2784
11
        shbuf[2] = ((shlen - 4)) >> 8 & 0xff;
2785
11
        shbuf[3] = (shlen - 4) & 0xff;
2786
11
        if (ossl_ech_intbuf_add(s, shbuf, shlen, hrr) != 1) {
2787
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2788
0
            return CON_FUNC_ERROR;
2789
0
        }
2790
11
        if (ossl_ech_calc_confirm(s, hrr, acbuf, shlen) != 1) {
2791
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2792
0
            return CON_FUNC_ERROR;
2793
0
        }
2794
11
        memcpy(s->s3.server_random + SSL3_RANDOM_SIZE - 8, acbuf, 8);
2795
11
        if (hrr == 0) {
2796
            /* confirm value hacked into SH.random rightmost octets */
2797
11
            shoffset = SSL3_HM_HEADER_LENGTH /* 4 */
2798
11
                + CLIENT_VERSION_LEN /* 2 */
2799
11
                + SSL3_RANDOM_SIZE /* 32 */
2800
11
                - 8;
2801
11
            memcpy(shbuf + shoffset, acbuf, 8);
2802
11
        } else {
2803
            /*
2804
             * confirm value is in extension in HRR case as the SH.random
2805
             * is already hacked to be a specific value in a HRR
2806
             */
2807
0
            memcpy(WPACKET_get_curr(pkt) - 8, acbuf, 8);
2808
0
        }
2809
11
    }
2810
    /* call ECH callback, if appropriate */
2811
3.15k
    if (s->ext.ech.attempted == 1 && s->ext.ech.cb != NULL
2812
0
        && s->hello_retry_request != SSL_HRR_PENDING) {
2813
0
        char pstr[OSSL_ECH_PBUF_SIZE + 1];
2814
0
        BIO *biom = BIO_new(BIO_s_mem());
2815
0
        unsigned int cbrv = 0;
2816
2817
0
        if (biom == NULL) {
2818
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2819
0
            return CON_FUNC_ERROR;
2820
0
        }
2821
0
        memset(pstr, 0, OSSL_ECH_PBUF_SIZE + 1);
2822
0
        ossl_ech_status_print(biom, s, OSSL_ECHSTORE_ALL);
2823
0
        BIO_read(biom, pstr, OSSL_ECH_PBUF_SIZE);
2824
0
        cbrv = s->ext.ech.cb(&s->ssl, pstr);
2825
0
        BIO_free(biom);
2826
0
        if (cbrv != 1) {
2827
0
            OSSL_TRACE(TLS, "Error from tls_construct_server_hello/ech_cb\n");
2828
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2829
0
            return CON_FUNC_ERROR;
2830
0
        }
2831
0
    }
2832
3.15k
#endif /* OPENSSL_NO_ECH */
2833
3.15k
    return CON_FUNC_SUCCESS;
2834
3.15k
}
2835
2836
CON_FUNC_RETURN tls_construct_server_done(SSL_CONNECTION *s, WPACKET *pkt)
2837
7.46k
{
2838
7.46k
    if (s->s3.tmp.cert_request == 0) {
2839
7.46k
        if (!ssl3_digest_cached_records(s, 0)) {
2840
            /* SSLfatal() already called */
2841
0
            return CON_FUNC_ERROR;
2842
0
        }
2843
7.46k
    }
2844
7.46k
    return CON_FUNC_SUCCESS;
2845
7.46k
}
2846
2847
CON_FUNC_RETURN tls_construct_server_key_exchange(SSL_CONNECTION *s,
2848
    WPACKET *pkt)
2849
5.14k
{
2850
5.14k
    EVP_PKEY *pkdh = NULL;
2851
5.14k
    unsigned char *encodedPoint = NULL;
2852
5.14k
    size_t encodedlen = 0;
2853
5.14k
    int group_id = 0;
2854
5.14k
    const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
2855
5.14k
    int i;
2856
5.14k
    unsigned long type;
2857
5.14k
    BIGNUM *r[4];
2858
5.14k
    EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2859
5.14k
    EVP_PKEY_CTX *pctx = NULL;
2860
5.14k
    size_t paramlen, paramoffset;
2861
5.14k
    int freer = 0;
2862
5.14k
    CON_FUNC_RETURN ret = CON_FUNC_ERROR;
2863
5.14k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2864
2865
5.14k
    if (!WPACKET_get_total_written(pkt, &paramoffset)) {
2866
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2867
0
        goto err;
2868
0
    }
2869
2870
5.14k
    if (md_ctx == NULL) {
2871
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2872
0
        goto err;
2873
0
    }
2874
2875
5.14k
    type = s->s3.tmp.new_cipher->algorithm_mkey;
2876
2877
5.14k
    r[0] = r[1] = r[2] = r[3] = NULL;
2878
5.14k
#ifndef OPENSSL_NO_PSK
2879
    /* Plain PSK or RSAPSK nothing to do */
2880
5.14k
    if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2881
0
    } else
2882
5.14k
#endif /* !OPENSSL_NO_PSK */
2883
5.14k
        if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2884
507
            CERT *cert = s->cert;
2885
507
            EVP_PKEY *pkdhp = NULL;
2886
2887
            /* Get NID of appropriate shared FFDHE group */
2888
507
            group_id = tls1_shared_group(s, TLS1_GROUPS_RETURN_TMP_ID,
2889
507
                TLS1_GROUPS_FFDHE_GROUPS);
2890
507
            if (group_id != 0) {
2891
                /* Cache the group used in the SSL_SESSION */
2892
507
                s->session->kex_group = group_id;
2893
2894
507
                s->s3.tmp.pkey = ssl_generate_pkey_group(s, group_id);
2895
507
                if (s->s3.tmp.pkey == NULL) {
2896
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2897
0
                    goto err;
2898
0
                }
2899
507
            } else {
2900
2901
0
                if (s->cert->dh_tmp_auto) {
2902
0
                    pkdh = ssl_get_auto_dh(s);
2903
0
                    if (pkdh == NULL) {
2904
0
                        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2905
0
                        goto err;
2906
0
                    }
2907
0
                    pkdhp = pkdh;
2908
0
                } else {
2909
0
                    pkdhp = cert->dh_tmp;
2910
0
                }
2911
0
#if !defined(OPENSSL_NO_DEPRECATED_3_0)
2912
0
                if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2913
0
                    pkdh = ssl_dh_to_pkey(
2914
0
                        s->cert->dh_tmp_cb(SSL_CONNECTION_GET_USER_SSL(s), 0, 1024));
2915
0
                    if (pkdh == NULL) {
2916
0
                        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2917
0
                        goto err;
2918
0
                    }
2919
0
                    pkdhp = pkdh;
2920
0
                }
2921
0
#endif
2922
0
                if (pkdhp == NULL) {
2923
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
2924
0
                    goto err;
2925
0
                }
2926
0
                if (!ssl_security(s, SSL_SECOP_TMP_DH,
2927
0
                        EVP_PKEY_get_security_bits(pkdhp), 0, pkdhp)) {
2928
0
                    SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
2929
0
                    goto err;
2930
0
                }
2931
0
                if (s->s3.tmp.pkey != NULL) {
2932
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2933
0
                    goto err;
2934
0
                }
2935
2936
0
                s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);
2937
0
                if (s->s3.tmp.pkey == NULL) {
2938
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2939
0
                    goto err;
2940
0
                }
2941
2942
0
                EVP_PKEY_free(pkdh);
2943
0
                pkdh = NULL;
2944
0
            }
2945
2946
            /* These BIGNUMs need to be freed when we're finished */
2947
507
            freer = 1;
2948
507
            if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,
2949
507
                    &r[0])
2950
507
                || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,
2951
507
                    &r[1])
2952
507
                || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,
2953
507
                    OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {
2954
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2955
0
                goto err;
2956
0
            }
2957
4.64k
        } else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2958
2959
4.64k
            if (s->s3.tmp.pkey != NULL) {
2960
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2961
0
                goto err;
2962
0
            }
2963
2964
            /* Get NID of appropriate shared ECDHE curve */
2965
4.64k
            group_id = tls1_shared_group(s, TLS1_GROUPS_RETURN_TMP_ID,
2966
4.64k
                TLS1_GROUPS_NON_FFDHE_GROUPS);
2967
4.64k
            if (group_id == 0) {
2968
0
                SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2969
0
                    SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2970
0
                goto err;
2971
0
            }
2972
            /* Cache the group used in the SSL_SESSION */
2973
4.64k
            s->session->kex_group = group_id;
2974
            /* Generate a new key for this curve */
2975
4.64k
            s->s3.tmp.pkey = ssl_generate_pkey_group(s, group_id);
2976
4.64k
            if (s->s3.tmp.pkey == NULL) {
2977
                /* SSLfatal() already called */
2978
0
                goto err;
2979
0
            }
2980
2981
            /* Encode the public key. */
2982
4.64k
            encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,
2983
4.64k
                &encodedPoint);
2984
4.64k
            if (encodedlen == 0) {
2985
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
2986
0
                goto err;
2987
0
            }
2988
2989
            /*
2990
             * We'll generate the serverKeyExchange message explicitly so we
2991
             * can set these to NULLs
2992
             */
2993
4.64k
            r[0] = NULL;
2994
4.64k
            r[1] = NULL;
2995
4.64k
            r[2] = NULL;
2996
4.64k
            r[3] = NULL;
2997
4.64k
        } else
2998
0
#ifndef OPENSSL_NO_SRP
2999
0
            if (type & SSL_kSRP) {
3000
0
            if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
3001
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);
3002
0
                goto err;
3003
0
            }
3004
0
            r[0] = s->srp_ctx.N;
3005
0
            r[1] = s->srp_ctx.g;
3006
0
            r[2] = s->srp_ctx.s;
3007
0
            r[3] = s->srp_ctx.B;
3008
0
        } else
3009
0
#endif
3010
0
        {
3011
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
3012
0
            goto err;
3013
0
        }
3014
3015
5.14k
    if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
3016
4.36k
        || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
3017
784
        lu = NULL;
3018
4.36k
    } else if (lu == NULL) {
3019
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
3020
0
        goto err;
3021
0
    }
3022
3023
5.14k
#ifndef OPENSSL_NO_PSK
3024
5.14k
    if (type & SSL_PSK) {
3025
0
        size_t len = (s->cert->psk_identity_hint == NULL)
3026
0
            ? 0
3027
0
            : strlen(s->cert->psk_identity_hint);
3028
3029
        /*
3030
         * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
3031
         * checked this when we set the identity hint - but just in case
3032
         */
3033
0
        if (len > PSK_MAX_IDENTITY_LEN
3034
0
            || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
3035
0
                len)) {
3036
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3037
0
            goto err;
3038
0
        }
3039
0
    }
3040
5.14k
#endif
3041
3042
6.66k
    for (i = 0; i < 4 && r[i] != NULL; i++) {
3043
1.52k
        unsigned char *binval;
3044
1.52k
        int res;
3045
3046
1.52k
#ifndef OPENSSL_NO_SRP
3047
1.52k
        if ((i == 2) && (type & SSL_kSRP)) {
3048
0
            res = WPACKET_start_sub_packet_u8(pkt);
3049
0
        } else
3050
1.52k
#endif
3051
1.52k
            res = WPACKET_start_sub_packet_u16(pkt);
3052
3053
1.52k
        if (!res) {
3054
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3055
0
            goto err;
3056
0
        }
3057
3058
        /*-
3059
         * for interoperability with some versions of the Microsoft TLS
3060
         * stack, we need to zero pad the DHE pub key to the same length
3061
         * as the prime
3062
         */
3063
1.52k
        if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
3064
507
            size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
3065
3066
507
            if (len > 0) {
3067
0
                if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
3068
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3069
0
                    goto err;
3070
0
                }
3071
0
                memset(binval, 0, len);
3072
0
            }
3073
507
        }
3074
3075
1.52k
        if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
3076
1.52k
            || !WPACKET_close(pkt)) {
3077
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3078
0
            goto err;
3079
0
        }
3080
3081
1.52k
        BN_bn2bin(r[i], binval);
3082
1.52k
    }
3083
3084
5.14k
    if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
3085
        /*
3086
         * We only support named (not generic) curves. In this situation, the
3087
         * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
3088
         * [1 byte length of encoded point], followed by the actual encoded
3089
         * point itself
3090
         */
3091
4.64k
        if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
3092
4.64k
            || !WPACKET_put_bytes_u16(pkt, group_id)
3093
4.64k
            || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
3094
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3095
0
            goto err;
3096
0
        }
3097
4.64k
        OPENSSL_free(encodedPoint);
3098
4.64k
        encodedPoint = NULL;
3099
4.64k
    }
3100
3101
    /* not anonymous */
3102
5.14k
    if (lu != NULL) {
3103
4.36k
        EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
3104
4.36k
        const EVP_MD *md;
3105
4.36k
        unsigned char *sigbytes1, *sigbytes2, *tbs;
3106
4.36k
        size_t siglen = 0, tbslen;
3107
3108
4.36k
        if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
3109
            /* Should never happen */
3110
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3111
0
            goto err;
3112
0
        }
3113
        /* Get length of the parameters we have written above */
3114
4.36k
        if (!WPACKET_get_length(pkt, &paramlen)) {
3115
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3116
0
            goto err;
3117
0
        }
3118
        /* send signature algorithm */
3119
4.36k
        if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
3120
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3121
0
            goto err;
3122
0
        }
3123
3124
4.36k
        if (EVP_DigestSignInit_ex(md_ctx, &pctx,
3125
4.36k
                md == NULL ? NULL : EVP_MD_get0_name(md),
3126
4.36k
                sctx->libctx, sctx->propq, pkey,
3127
4.36k
                NULL)
3128
4.36k
            <= 0) {
3129
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3130
0
            goto err;
3131
0
        }
3132
4.36k
        if (lu->sig == EVP_PKEY_RSA_PSS) {
3133
362
            if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
3134
362
                || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
3135
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3136
0
                goto err;
3137
0
            }
3138
362
        }
3139
4.36k
        tbslen = construct_key_exchange_tbs(s, &tbs,
3140
4.36k
            s->init_buf->data + paramoffset,
3141
4.36k
            paramlen);
3142
4.36k
        if (tbslen == 0) {
3143
            /* SSLfatal() already called */
3144
0
            goto err;
3145
0
        }
3146
3147
4.36k
        if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <= 0
3148
4.36k
            || !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
3149
4.36k
            || EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 0
3150
4.34k
            || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
3151
4.34k
            || sigbytes1 != sigbytes2) {
3152
22
            OPENSSL_free(tbs);
3153
22
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3154
22
            goto err;
3155
22
        }
3156
4.34k
        OPENSSL_free(tbs);
3157
4.34k
    }
3158
3159
5.12k
    ret = CON_FUNC_SUCCESS;
3160
5.14k
err:
3161
5.14k
    EVP_PKEY_free(pkdh);
3162
5.14k
    OPENSSL_free(encodedPoint);
3163
5.14k
    EVP_MD_CTX_free(md_ctx);
3164
5.14k
    if (freer) {
3165
507
        BN_free(r[0]);
3166
507
        BN_free(r[1]);
3167
507
        BN_free(r[2]);
3168
507
        BN_free(r[3]);
3169
507
    }
3170
5.14k
    return ret;
3171
5.12k
}
3172
3173
CON_FUNC_RETURN tls_construct_certificate_request(SSL_CONNECTION *s,
3174
    WPACKET *pkt)
3175
0
{
3176
0
    if (SSL_CONNECTION_IS_TLS13(s)) {
3177
        /* Send random context when doing post-handshake auth */
3178
0
        if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
3179
0
            OPENSSL_free(s->pha_context);
3180
0
            s->pha_context_len = 32;
3181
0
            if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {
3182
0
                s->pha_context_len = 0;
3183
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3184
0
                return CON_FUNC_ERROR;
3185
0
            }
3186
0
            if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
3187
0
                    s->pha_context, s->pha_context_len, 0)
3188
0
                    <= 0
3189
0
                || !WPACKET_sub_memcpy_u8(pkt, s->pha_context,
3190
0
                    s->pha_context_len)) {
3191
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3192
0
                return CON_FUNC_ERROR;
3193
0
            }
3194
            /* reset the handshake hash back to just after the ClientFinished */
3195
0
            if (!tls13_restore_handshake_digest_for_pha(s)) {
3196
                /* SSLfatal() already called */
3197
0
                return CON_FUNC_ERROR;
3198
0
            }
3199
0
        } else {
3200
0
            if (!WPACKET_put_bytes_u8(pkt, 0)) {
3201
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3202
0
                return CON_FUNC_ERROR;
3203
0
            }
3204
0
        }
3205
3206
0
        if (!tls_construct_extensions(s, pkt,
3207
0
                SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
3208
0
                0)) {
3209
            /* SSLfatal() already called */
3210
0
            return CON_FUNC_ERROR;
3211
0
        }
3212
0
        goto done;
3213
0
    }
3214
3215
    /* get the list of acceptable cert types */
3216
0
    if (!WPACKET_start_sub_packet_u8(pkt)
3217
0
        || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
3218
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3219
0
        return CON_FUNC_ERROR;
3220
0
    }
3221
3222
0
    if (SSL_USE_SIGALGS(s)) {
3223
0
        const uint16_t *psigs;
3224
0
        size_t nl = tls12_get_psigalgs(s, 1, &psigs);
3225
3226
0
        if (!WPACKET_start_sub_packet_u16(pkt)
3227
0
            || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
3228
0
            || !tls12_copy_sigalgs(s, pkt, psigs, nl)
3229
0
            || !WPACKET_close(pkt)) {
3230
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3231
0
            return CON_FUNC_ERROR;
3232
0
        }
3233
0
    }
3234
3235
0
    if (!construct_ca_names(s, get_ca_names(s), pkt)) {
3236
        /* SSLfatal() already called */
3237
0
        return CON_FUNC_ERROR;
3238
0
    }
3239
3240
0
done:
3241
0
    s->certreqs_sent++;
3242
0
    s->s3.tmp.cert_request = 1;
3243
0
    return CON_FUNC_SUCCESS;
3244
0
}
3245
3246
static int tls_process_cke_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)
3247
0
{
3248
0
#ifndef OPENSSL_NO_PSK
3249
0
    unsigned char psk[PSK_MAX_PSK_LEN];
3250
0
    size_t psklen;
3251
0
    PACKET psk_identity;
3252
3253
0
    if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
3254
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3255
0
        return 0;
3256
0
    }
3257
0
    if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
3258
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);
3259
0
        return 0;
3260
0
    }
3261
0
    if (s->psk_server_callback == NULL) {
3262
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);
3263
0
        return 0;
3264
0
    }
3265
3266
0
    if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
3267
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3268
0
        return 0;
3269
0
    }
3270
3271
0
    psklen = s->psk_server_callback(SSL_CONNECTION_GET_USER_SSL(s),
3272
0
        s->session->psk_identity,
3273
0
        psk, sizeof(psk));
3274
3275
0
    if (psklen > PSK_MAX_PSK_LEN) {
3276
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3277
0
        return 0;
3278
0
    } else if (psklen == 0) {
3279
        /*
3280
         * PSK related to the given identity not found
3281
         */
3282
0
        SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);
3283
0
        return 0;
3284
0
    }
3285
3286
0
    OPENSSL_free(s->s3.tmp.psk);
3287
0
    s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
3288
0
    OPENSSL_cleanse(psk, psklen);
3289
3290
0
    if (s->s3.tmp.psk == NULL) {
3291
0
        s->s3.tmp.psklen = 0;
3292
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3293
0
        return 0;
3294
0
    }
3295
3296
0
    s->s3.tmp.psklen = psklen;
3297
3298
0
    return 1;
3299
#else
3300
    /* Should never happen */
3301
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3302
    return 0;
3303
#endif
3304
0
}
3305
3306
static int tls_process_cke_rsa(SSL_CONNECTION *s, PACKET *pkt)
3307
1.72k
{
3308
1.72k
    size_t outlen;
3309
1.72k
    PACKET enc_premaster;
3310
1.72k
    EVP_PKEY *rsa = NULL;
3311
1.72k
    unsigned char *rsa_decrypt = NULL;
3312
1.72k
    int ret = 0;
3313
1.72k
    EVP_PKEY_CTX *ctx = NULL;
3314
1.72k
    OSSL_PARAM params[3], *p = params;
3315
1.72k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3316
3317
1.72k
    rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
3318
1.72k
    if (rsa == NULL) {
3319
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);
3320
0
        return 0;
3321
0
    }
3322
3323
    /* pre-standard DTLS omits the length bytes. */
3324
1.72k
    if (s->version == DTLS1_BAD_VER) {
3325
0
        enc_premaster = *pkt;
3326
1.72k
    } else {
3327
1.72k
        if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
3328
1.68k
            || PACKET_remaining(pkt) != 0) {
3329
53
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3330
53
            return 0;
3331
53
        }
3332
1.72k
    }
3333
3334
1.67k
    outlen = SSL_MAX_MASTER_KEY_LENGTH;
3335
1.67k
    rsa_decrypt = OPENSSL_malloc(outlen);
3336
1.67k
    if (rsa_decrypt == NULL) {
3337
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3338
0
        return 0;
3339
0
    }
3340
3341
1.67k
    ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, rsa, sctx->propq);
3342
1.67k
    if (ctx == NULL) {
3343
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3344
0
        goto err;
3345
0
    }
3346
3347
    /*
3348
     * We must not leak whether a decryption failure occurs because of
3349
     * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
3350
     * section 7.4.7.1). We use the special padding type
3351
     * RSA_PKCS1_WITH_TLS_PADDING to do that. It will automatically decrypt the
3352
     * RSA, check the padding and check that the client version is as expected
3353
     * in the premaster secret. If any of that fails then the function appears
3354
     * to return successfully but with a random result. The call below could
3355
     * still fail if the input is publicly invalid.
3356
     * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
3357
     */
3358
1.67k
    if (EVP_PKEY_decrypt_init(ctx) <= 0
3359
1.67k
        || EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {
3360
0
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3361
0
        goto err;
3362
0
    }
3363
3364
1.67k
    *p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,
3365
1.67k
        (unsigned int *)&s->client_version);
3366
1.67k
    if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)
3367
0
        *p++ = OSSL_PARAM_construct_uint(
3368
0
            OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,
3369
0
            (unsigned int *)&s->version);
3370
1.67k
    *p++ = OSSL_PARAM_construct_end();
3371
3372
1.67k
    if (!EVP_PKEY_CTX_set_params(ctx, params)
3373
1.67k
        || EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,
3374
1.67k
               PACKET_data(&enc_premaster),
3375
1.67k
               PACKET_remaining(&enc_premaster))
3376
1.67k
            <= 0) {
3377
9
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3378
9
        goto err;
3379
9
    }
3380
3381
    /*
3382
     * This test should never fail (otherwise we should have failed above) but
3383
     * we double check anyway.
3384
     */
3385
1.66k
    if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {
3386
0
        OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);
3387
0
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3388
0
        goto err;
3389
0
    }
3390
3391
    /* Also cleanses rsa_decrypt (on success or failure) */
3392
1.66k
    if (!ssl_generate_master_secret(s, rsa_decrypt, outlen, 0)) {
3393
        /* SSLfatal() already called */
3394
0
        goto err;
3395
0
    }
3396
3397
1.66k
    ret = 1;
3398
1.67k
err:
3399
1.67k
    OPENSSL_free(rsa_decrypt);
3400
1.67k
    EVP_PKEY_CTX_free(ctx);
3401
1.67k
    return ret;
3402
1.66k
}
3403
3404
static int tls_process_cke_dhe(SSL_CONNECTION *s, PACKET *pkt)
3405
184
{
3406
184
    EVP_PKEY *skey = NULL;
3407
184
    unsigned int i;
3408
184
    const unsigned char *data;
3409
184
    EVP_PKEY *ckey = NULL;
3410
184
    int ret = 0;
3411
3412
184
    if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
3413
39
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
3414
39
        goto err;
3415
39
    }
3416
145
    skey = s->s3.tmp.pkey;
3417
145
    if (skey == NULL) {
3418
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3419
0
        goto err;
3420
0
    }
3421
3422
145
    if (PACKET_remaining(pkt) == 0L) {
3423
2
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3424
2
        goto err;
3425
2
    }
3426
143
    if (!PACKET_get_bytes(pkt, &data, i)) {
3427
        /* We already checked we have enough data */
3428
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3429
0
        goto err;
3430
0
    }
3431
143
    ckey = EVP_PKEY_new();
3432
143
    if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3433
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3434
0
        goto err;
3435
0
    }
3436
3437
143
    if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3438
7
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3439
7
        goto err;
3440
7
    }
3441
3442
136
    if (ssl_derive(s, skey, ckey, 1) == 0) {
3443
        /* SSLfatal() already called */
3444
0
        goto err;
3445
0
    }
3446
3447
136
    ret = 1;
3448
136
    EVP_PKEY_free(s->s3.tmp.pkey);
3449
136
    s->s3.tmp.pkey = NULL;
3450
184
err:
3451
184
    EVP_PKEY_free(ckey);
3452
184
    return ret;
3453
136
}
3454
3455
static int tls_process_cke_ecdhe(SSL_CONNECTION *s, PACKET *pkt)
3456
4.25k
{
3457
4.25k
    EVP_PKEY *skey = s->s3.tmp.pkey;
3458
4.25k
    EVP_PKEY *ckey = NULL;
3459
4.25k
    int ret = 0;
3460
3461
4.25k
    if (PACKET_remaining(pkt) == 0L) {
3462
        /* We don't support ECDH client auth */
3463
15
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);
3464
15
        goto err;
3465
4.23k
    } else {
3466
4.23k
        unsigned int i;
3467
4.23k
        const unsigned char *data;
3468
3469
        /*
3470
         * Get client's public key from encoded point in the
3471
         * ClientKeyExchange message.
3472
         */
3473
3474
        /*
3475
         * Get encoded point length
3476
         * empty key should be handled here
3477
         */
3478
4.23k
        if (!PACKET_get_1(pkt, &i) || i == 0 || !PACKET_get_bytes(pkt, &data, i)
3479
4.17k
            || PACKET_remaining(pkt) != 0) {
3480
94
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3481
94
            goto err;
3482
94
        }
3483
4.14k
        if (skey == NULL) {
3484
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);
3485
0
            goto err;
3486
0
        }
3487
3488
4.14k
        ckey = EVP_PKEY_new();
3489
4.14k
        if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3490
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3491
0
            goto err;
3492
0
        }
3493
3494
4.14k
        if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3495
838
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3496
838
            goto err;
3497
838
        }
3498
4.14k
    }
3499
3500
3.30k
    if (ssl_derive(s, skey, ckey, 1) == 0) {
3501
        /* SSLfatal() already called */
3502
25
        goto err;
3503
25
    }
3504
3505
3.28k
    ret = 1;
3506
3.28k
    EVP_PKEY_free(s->s3.tmp.pkey);
3507
3.28k
    s->s3.tmp.pkey = NULL;
3508
4.25k
err:
3509
4.25k
    EVP_PKEY_free(ckey);
3510
3511
4.25k
    return ret;
3512
3.28k
}
3513
3514
static int tls_process_cke_srp(SSL_CONNECTION *s, PACKET *pkt)
3515
0
{
3516
0
#ifndef OPENSSL_NO_SRP
3517
0
    unsigned int i;
3518
0
    const unsigned char *data;
3519
3520
0
    if (!PACKET_get_net_2(pkt, &i)
3521
0
        || !PACKET_get_bytes(pkt, &data, i)) {
3522
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);
3523
0
        return 0;
3524
0
    }
3525
0
    if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3526
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
3527
0
        return 0;
3528
0
    }
3529
0
    if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3530
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);
3531
0
        return 0;
3532
0
    }
3533
0
    OPENSSL_free(s->session->srp_username);
3534
0
    s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3535
0
    if (s->session->srp_username == NULL) {
3536
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3537
0
        return 0;
3538
0
    }
3539
3540
0
    if (!srp_generate_server_master_secret(s)) {
3541
        /* SSLfatal() already called */
3542
0
        return 0;
3543
0
    }
3544
3545
0
    return 1;
3546
#else
3547
    /* Should never happen */
3548
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3549
    return 0;
3550
#endif
3551
0
}
3552
3553
static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)
3554
0
{
3555
0
#ifndef OPENSSL_NO_GOST
3556
0
    EVP_PKEY_CTX *pkey_ctx;
3557
0
    EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3558
0
    unsigned char premaster_secret[32];
3559
0
    const unsigned char *start;
3560
0
    size_t outlen = sizeof(premaster_secret), inlen;
3561
0
    unsigned long alg_a;
3562
0
    GOST_KX_MESSAGE *pKX = NULL;
3563
0
    const unsigned char *ptr;
3564
0
    int ret = 0;
3565
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3566
3567
    /* Get our certificate private key */
3568
0
    alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3569
0
    if (alg_a & SSL_aGOST12) {
3570
        /*
3571
         * New GOST ciphersuites have SSL_aGOST01 bit too
3572
         */
3573
0
        pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3574
0
        if (pk == NULL) {
3575
0
            pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3576
0
        }
3577
0
        if (pk == NULL) {
3578
0
            pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3579
0
        }
3580
0
    } else if (alg_a & SSL_aGOST01) {
3581
0
        pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3582
0
    }
3583
3584
0
    pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3585
0
    if (pkey_ctx == NULL) {
3586
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3587
0
        return 0;
3588
0
    }
3589
0
    if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3590
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3591
0
        goto err;
3592
0
    }
3593
    /*
3594
     * If client certificate is present and is of the same type, maybe
3595
     * use it for key exchange.  Don't mind errors from
3596
     * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3597
     * client certificate for authorization only.
3598
     */
3599
0
    client_pub_pkey = tls_get_peer_pkey(s);
3600
0
    if (client_pub_pkey) {
3601
0
        if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3602
0
            ERR_clear_error();
3603
0
    }
3604
3605
0
    ptr = PACKET_data(pkt);
3606
    /* Some implementations provide extra data in the opaqueBlob
3607
     * We have nothing to do with this blob so we just skip it */
3608
0
    pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, (long)PACKET_remaining(pkt));
3609
0
    if (pKX == NULL
3610
0
        || pKX->kxBlob == NULL
3611
0
        || ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {
3612
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3613
0
        goto err;
3614
0
    }
3615
3616
0
    if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {
3617
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3618
0
        goto err;
3619
0
    }
3620
3621
0
    if (PACKET_remaining(pkt) != 0) {
3622
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3623
0
        goto err;
3624
0
    }
3625
3626
0
    inlen = ASN1_STRING_length(pKX->kxBlob->value.sequence);
3627
0
    start = ASN1_STRING_get0_data(pKX->kxBlob->value.sequence);
3628
3629
0
    if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3630
0
            inlen)
3631
0
        <= 0) {
3632
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3633
0
        goto err;
3634
0
    }
3635
    /* Generate master secret */
3636
0
    if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3637
        /* SSLfatal() already called */
3638
0
        goto err;
3639
0
    }
3640
    /* Check if pubkey from client certificate was used */
3641
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3642
0
            NULL)
3643
0
        > 0)
3644
0
        s->statem.no_cert_verify = 1;
3645
3646
0
    ret = 1;
3647
0
err:
3648
0
    EVP_PKEY_CTX_free(pkey_ctx);
3649
0
    GOST_KX_MESSAGE_free(pKX);
3650
0
    return ret;
3651
#else
3652
    /* Should never happen */
3653
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3654
    return 0;
3655
#endif
3656
0
}
3657
3658
static int tls_process_cke_gost18(SSL_CONNECTION *s, PACKET *pkt)
3659
0
{
3660
0
#ifndef OPENSSL_NO_GOST
3661
0
    unsigned char rnd_dgst[32];
3662
0
    EVP_PKEY_CTX *pkey_ctx = NULL;
3663
0
    EVP_PKEY *pk = NULL;
3664
0
    unsigned char premaster_secret[32];
3665
0
    const unsigned char *start = NULL;
3666
0
    size_t outlen = sizeof(premaster_secret), inlen = 0;
3667
0
    int ret = 0;
3668
0
    int cipher_nid = ossl_gost18_cke_cipher_nid(s);
3669
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3670
3671
0
    if (cipher_nid == NID_undef) {
3672
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3673
0
        return 0;
3674
0
    }
3675
3676
0
    if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
3677
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3678
0
        goto err;
3679
0
    }
3680
3681
    /* Get our certificate private key */
3682
0
    pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey != NULL ? s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey : s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3683
0
    if (pk == NULL) {
3684
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
3685
0
        goto err;
3686
0
    }
3687
3688
0
    pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3689
0
    if (pkey_ctx == NULL) {
3690
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3691
0
        goto err;
3692
0
    }
3693
0
    if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3694
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3695
0
        goto err;
3696
0
    }
3697
3698
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3699
0
            EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst)
3700
0
        <= 0) {
3701
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3702
0
        goto err;
3703
0
    }
3704
3705
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3706
0
            EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL)
3707
0
        <= 0) {
3708
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3709
0
        goto err;
3710
0
    }
3711
0
    inlen = PACKET_remaining(pkt);
3712
0
    start = PACKET_data(pkt);
3713
3714
0
    if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3715
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3716
0
        goto err;
3717
0
    }
3718
    /* Generate master secret */
3719
0
    if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3720
        /* SSLfatal() already called */
3721
0
        goto err;
3722
0
    }
3723
0
    ret = 1;
3724
3725
0
err:
3726
0
    EVP_PKEY_CTX_free(pkey_ctx);
3727
0
    return ret;
3728
#else
3729
    /* Should never happen */
3730
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3731
    return 0;
3732
#endif
3733
0
}
3734
3735
MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL_CONNECTION *s,
3736
    PACKET *pkt)
3737
14.8k
{
3738
14.8k
    unsigned long alg_k;
3739
3740
14.8k
    alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3741
3742
    /* For PSK parse and retrieve identity, obtain PSK key */
3743
14.8k
    if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3744
        /* SSLfatal() already called */
3745
0
        goto err;
3746
0
    }
3747
3748
14.8k
    if (alg_k & SSL_kPSK) {
3749
        /* Identity extracted earlier: should be nothing left */
3750
0
        if (PACKET_remaining(pkt) != 0) {
3751
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3752
0
            goto err;
3753
0
        }
3754
        /* PSK handled by ssl_generate_master_secret */
3755
0
        if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3756
            /* SSLfatal() already called */
3757
0
            goto err;
3758
0
        }
3759
14.8k
    } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3760
8.26k
        if (!tls_process_cke_rsa(s, pkt)) {
3761
            /* SSLfatal() already called */
3762
218
            goto err;
3763
218
        }
3764
8.26k
    } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3765
184
        if (!tls_process_cke_dhe(s, pkt)) {
3766
            /* SSLfatal() already called */
3767
48
            goto err;
3768
48
        }
3769
6.44k
    } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3770
6.44k
        if (!tls_process_cke_ecdhe(s, pkt)) {
3771
            /* SSLfatal() already called */
3772
1.40k
            goto err;
3773
1.40k
        }
3774
6.44k
    } else if (alg_k & SSL_kSRP) {
3775
0
        if (!tls_process_cke_srp(s, pkt)) {
3776
            /* SSLfatal() already called */
3777
0
            goto err;
3778
0
        }
3779
0
    } else if (alg_k & SSL_kGOST) {
3780
0
        if (!tls_process_cke_gost(s, pkt)) {
3781
            /* SSLfatal() already called */
3782
0
            goto err;
3783
0
        }
3784
0
    } else if (alg_k & SSL_kGOST18) {
3785
0
        if (!tls_process_cke_gost18(s, pkt)) {
3786
            /* SSLfatal() already called */
3787
0
            goto err;
3788
0
        }
3789
0
    } else {
3790
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
3791
0
        goto err;
3792
0
    }
3793
3794
13.2k
    return MSG_PROCESS_CONTINUE_PROCESSING;
3795
1.67k
err:
3796
1.67k
#ifndef OPENSSL_NO_PSK
3797
1.67k
    OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3798
1.67k
    s->s3.tmp.psk = NULL;
3799
1.67k
    s->s3.tmp.psklen = 0;
3800
1.67k
#endif
3801
1.67k
    return MSG_PROCESS_ERROR;
3802
14.8k
}
3803
3804
WORK_STATE tls_post_process_client_key_exchange(SSL_CONNECTION *s,
3805
    WORK_STATE wst)
3806
13.2k
{
3807
#ifndef OPENSSL_NO_SCTP
3808
    if (wst == WORK_MORE_A) {
3809
        if (SSL_CONNECTION_IS_DTLS(s)) {
3810
            unsigned char sctpauthkey[64];
3811
            char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3812
            size_t labellen;
3813
            /*
3814
             * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3815
             * used.
3816
             */
3817
            memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3818
                sizeof(DTLS1_SCTP_AUTH_LABEL));
3819
3820
            /* Don't include the terminating zero. */
3821
            labellen = sizeof(labelbuffer) - 1;
3822
            if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3823
                labellen += 1;
3824
3825
            if (SSL_export_keying_material(SSL_CONNECTION_GET_SSL(s),
3826
                    sctpauthkey,
3827
                    sizeof(sctpauthkey), labelbuffer,
3828
                    labellen, NULL, 0,
3829
                    0)
3830
                <= 0) {
3831
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3832
                return WORK_ERROR;
3833
            }
3834
3835
            BIO_ctrl(s->wbio, BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3836
                sizeof(sctpauthkey), sctpauthkey);
3837
        }
3838
    }
3839
#endif
3840
3841
13.2k
    if (s->statem.no_cert_verify || !received_client_cert(s)) {
3842
        /*
3843
         * No certificate verify or no peer certificate so we no longer need
3844
         * the handshake_buffer
3845
         */
3846
13.2k
        if (!ssl3_digest_cached_records(s, 0)) {
3847
            /* SSLfatal() already called */
3848
0
            return WORK_ERROR;
3849
0
        }
3850
13.2k
        return WORK_FINISHED_CONTINUE;
3851
13.2k
    } else {
3852
0
        if (!s->s3.handshake_buffer) {
3853
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3854
0
            return WORK_ERROR;
3855
0
        }
3856
        /*
3857
         * For sigalgs freeze the handshake buffer. If we support
3858
         * extms we've done this already so this is a no-op
3859
         */
3860
0
        if (!ssl3_digest_cached_records(s, 1)) {
3861
            /* SSLfatal() already called */
3862
0
            return WORK_ERROR;
3863
0
        }
3864
0
    }
3865
3866
0
    return WORK_FINISHED_CONTINUE;
3867
13.2k
}
3868
3869
MSG_PROCESS_RETURN tls_process_client_rpk(SSL_CONNECTION *sc, PACKET *pkt)
3870
0
{
3871
0
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3872
0
    SSL_SESSION *new_sess = NULL;
3873
0
    EVP_PKEY *peer_rpk = NULL;
3874
3875
0
    if (!tls_process_rpk(sc, pkt, &peer_rpk)) {
3876
        /* SSLfatal already called */
3877
0
        goto err;
3878
0
    }
3879
3880
0
    if (peer_rpk == NULL) {
3881
0
        if ((sc->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
3882
0
            && (sc->verify_mode & SSL_VERIFY_PEER)) {
3883
0
            SSLfatal(sc, SSL_AD_CERTIFICATE_REQUIRED,
3884
0
                SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3885
0
            goto err;
3886
0
        }
3887
0
    } else {
3888
0
        if (ssl_verify_rpk(sc, peer_rpk) <= 0) {
3889
0
            SSLfatal(sc, ssl_x509err2alert(sc->verify_result),
3890
0
                SSL_R_CERTIFICATE_VERIFY_FAILED);
3891
0
            goto err;
3892
0
        }
3893
0
    }
3894
3895
    /*
3896
     * Sessions must be immutable once they go into the session cache. Otherwise
3897
     * we can get multi-thread problems. Therefore we don't "update" sessions,
3898
     * we replace them with a duplicate. Here, we need to do this every time
3899
     * a new RPK (or certificate) is received via post-handshake authentication,
3900
     * as the session may have already gone into the session cache.
3901
     */
3902
3903
0
    if (sc->post_handshake_auth == SSL_PHA_REQUESTED) {
3904
0
        if ((new_sess = ssl_session_dup(sc->session, 0)) == NULL) {
3905
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3906
0
            goto err;
3907
0
        }
3908
3909
0
        SSL_SESSION_free(sc->session);
3910
0
        sc->session = new_sess;
3911
0
    }
3912
3913
    /* Ensure there is no peer/peer_chain */
3914
0
    X509_free(sc->session->peer);
3915
0
    sc->session->peer = NULL;
3916
0
    sk_X509_pop_free(sc->session->peer_chain, X509_free);
3917
0
    sc->session->peer_chain = NULL;
3918
    /* Save RPK */
3919
0
    EVP_PKEY_free(sc->session->peer_rpk);
3920
0
    sc->session->peer_rpk = peer_rpk;
3921
0
    peer_rpk = NULL;
3922
3923
0
    sc->session->verify_result = sc->verify_result;
3924
3925
    /*
3926
     * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3927
     * message
3928
     */
3929
0
    if (SSL_CONNECTION_IS_TLS13(sc)) {
3930
0
        if (!ssl3_digest_cached_records(sc, 1)) {
3931
            /* SSLfatal() already called */
3932
0
            goto err;
3933
0
        }
3934
3935
        /* Save the current hash state for when we receive the CertificateVerify */
3936
0
        if (!ssl_handshake_hash(sc, sc->cert_verify_hash,
3937
0
                sizeof(sc->cert_verify_hash),
3938
0
                &sc->cert_verify_hash_len)) {
3939
0
            /* SSLfatal() already called */;
3940
0
            goto err;
3941
0
        }
3942
3943
        /* resend session tickets */
3944
0
        sc->sent_tickets = 0;
3945
0
    }
3946
3947
0
    ret = MSG_PROCESS_CONTINUE_READING;
3948
3949
0
err:
3950
0
    EVP_PKEY_free(peer_rpk);
3951
0
    return ret;
3952
0
}
3953
3954
MSG_PROCESS_RETURN tls_process_client_certificate(SSL_CONNECTION *s,
3955
    PACKET *pkt)
3956
0
{
3957
0
    int i;
3958
0
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3959
0
    X509 *x = NULL;
3960
0
    unsigned long l;
3961
0
    const unsigned char *certstart, *certbytes;
3962
0
    STACK_OF(X509) *sk = NULL;
3963
0
    PACKET spkt, context;
3964
0
    size_t chainidx;
3965
0
    SSL_SESSION *new_sess = NULL;
3966
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3967
3968
    /*
3969
     * To get this far we must have read encrypted data from the client. We no
3970
     * longer tolerate unencrypted alerts. This is ignored if less than TLSv1.3
3971
     */
3972
0
    if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
3973
0
        s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
3974
3975
0
    if (s->ext.client_cert_type == TLSEXT_cert_type_rpk)
3976
0
        return tls_process_client_rpk(s, pkt);
3977
3978
0
    if (s->ext.client_cert_type != TLSEXT_cert_type_x509) {
3979
0
        SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,
3980
0
            SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3981
0
        goto err;
3982
0
    }
3983
3984
0
    if ((sk = sk_X509_new_null()) == NULL) {
3985
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3986
0
        goto err;
3987
0
    }
3988
3989
0
    if (SSL_CONNECTION_IS_TLS13(s)
3990
0
        && (!PACKET_get_length_prefixed_1(pkt, &context)
3991
0
            || (s->pha_context == NULL && PACKET_remaining(&context) != 0)
3992
0
            || (s->pha_context != NULL
3993
0
                && !PACKET_equal(&context, s->pha_context,
3994
0
                    s->pha_context_len)))) {
3995
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
3996
0
        goto err;
3997
0
    }
3998
3999
0
    if (!PACKET_get_length_prefixed_3(pkt, &spkt)
4000
0
        || PACKET_remaining(pkt) != 0) {
4001
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4002
0
        goto err;
4003
0
    }
4004
4005
0
    for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
4006
0
        if (!PACKET_get_net_3(&spkt, &l)
4007
0
            || !PACKET_get_bytes(&spkt, &certbytes, l)) {
4008
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
4009
0
            goto err;
4010
0
        }
4011
4012
0
        certstart = certbytes;
4013
0
        x = X509_new_ex(sctx->libctx, sctx->propq);
4014
0
        if (x == NULL) {
4015
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_X509_LIB);
4016
0
            goto err;
4017
0
        }
4018
0
        if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {
4019
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
4020
0
            goto err;
4021
0
        }
4022
4023
0
        if (certbytes != (certstart + l)) {
4024
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
4025
0
            goto err;
4026
0
        }
4027
4028
0
        if (SSL_CONNECTION_IS_TLS13(s)) {
4029
0
            RAW_EXTENSION *rawexts = NULL;
4030
0
            PACKET extensions;
4031
4032
0
            if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
4033
0
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
4034
0
                goto err;
4035
0
            }
4036
0
            if (!tls_collect_extensions(s, &extensions,
4037
0
                    SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
4038
0
                    NULL, chainidx == 0)
4039
0
                || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
4040
0
                    rawexts, x, chainidx,
4041
0
                    PACKET_remaining(&spkt) == 0)) {
4042
0
                OPENSSL_free(rawexts);
4043
0
                goto err;
4044
0
            }
4045
0
            OPENSSL_free(rawexts);
4046
0
        }
4047
4048
0
        if (!sk_X509_push(sk, x)) {
4049
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4050
0
            goto err;
4051
0
        }
4052
0
        x = NULL;
4053
0
    }
4054
4055
0
    if (sk_X509_num(sk) <= 0) {
4056
        /* Fail only if we required a certificate */
4057
0
        if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
4058
0
            SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
4059
0
                SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
4060
0
            goto err;
4061
0
        }
4062
        /* No client certificate so digest cached records */
4063
0
        if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
4064
            /* SSLfatal() already called */
4065
0
            goto err;
4066
0
        }
4067
0
    } else {
4068
0
        EVP_PKEY *pkey;
4069
0
        i = ssl_verify_cert_chain(s, sk);
4070
0
        if (i <= 0) {
4071
0
            SSLfatal(s, ssl_x509err2alert(s->verify_result),
4072
0
                SSL_R_CERTIFICATE_VERIFY_FAILED);
4073
0
            goto err;
4074
0
        }
4075
0
        pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
4076
0
        if (pkey == NULL) {
4077
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
4078
0
                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
4079
0
            goto err;
4080
0
        }
4081
0
    }
4082
4083
    /*
4084
     * Sessions must be immutable once they go into the session cache. Otherwise
4085
     * we can get multi-thread problems. Therefore we don't "update" sessions,
4086
     * we replace them with a duplicate. Here, we need to do this every time
4087
     * a new certificate is received via post-handshake authentication, as the
4088
     * session may have already gone into the session cache.
4089
     */
4090
4091
0
    if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
4092
0
        if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
4093
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
4094
0
            goto err;
4095
0
        }
4096
4097
0
        SSL_SESSION_free(s->session);
4098
0
        s->session = new_sess;
4099
0
    }
4100
4101
0
    X509_free(s->session->peer);
4102
0
    s->session->peer = sk_X509_shift(sk);
4103
0
    s->session->verify_result = s->verify_result;
4104
4105
0
    OSSL_STACK_OF_X509_free(s->session->peer_chain);
4106
0
    s->session->peer_chain = sk;
4107
0
    sk = NULL;
4108
    /* Ensure there is no RPK */
4109
0
    EVP_PKEY_free(s->session->peer_rpk);
4110
0
    s->session->peer_rpk = NULL;
4111
4112
    /*
4113
     * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
4114
     * message
4115
     */
4116
0
    if (SSL_CONNECTION_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
4117
        /* SSLfatal() already called */
4118
0
        goto err;
4119
0
    }
4120
4121
    /*
4122
     * Inconsistency alert: cert_chain does *not* include the peer's own
4123
     * certificate, while we do include it in statem_clnt.c
4124
     */
4125
4126
    /* Save the current hash state for when we receive the CertificateVerify */
4127
0
    if (SSL_CONNECTION_IS_TLS13(s)) {
4128
0
        if (!ssl_handshake_hash(s, s->cert_verify_hash,
4129
0
                sizeof(s->cert_verify_hash),
4130
0
                &s->cert_verify_hash_len)) {
4131
            /* SSLfatal() already called */
4132
0
            goto err;
4133
0
        }
4134
4135
        /* Resend session tickets */
4136
0
        s->sent_tickets = 0;
4137
0
    }
4138
4139
0
    ret = MSG_PROCESS_CONTINUE_READING;
4140
4141
0
err:
4142
0
    X509_free(x);
4143
0
    OSSL_STACK_OF_X509_free(sk);
4144
0
    return ret;
4145
0
}
4146
4147
#ifndef OPENSSL_NO_COMP_ALG
4148
MSG_PROCESS_RETURN tls_process_client_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)
4149
{
4150
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
4151
    PACKET tmppkt;
4152
    BUF_MEM *buf = BUF_MEM_new();
4153
4154
    if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)
4155
        ret = tls_process_client_certificate(sc, &tmppkt);
4156
4157
    BUF_MEM_free(buf);
4158
    return ret;
4159
}
4160
#endif
4161
4162
CON_FUNC_RETURN tls_construct_server_certificate(SSL_CONNECTION *s, WPACKET *pkt)
4163
15.7k
{
4164
15.7k
    CERT_PKEY *cpk = s->s3.tmp.cert;
4165
4166
15.7k
    if (cpk == NULL) {
4167
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4168
0
        return CON_FUNC_ERROR;
4169
0
    }
4170
4171
    /*
4172
     * In TLSv1.3 the certificate chain is always preceded by a 0 length context
4173
     * for the server Certificate message
4174
     */
4175
15.7k
    if (SSL_CONNECTION_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
4176
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4177
0
        return CON_FUNC_ERROR;
4178
0
    }
4179
15.7k
    switch (s->ext.server_cert_type) {
4180
0
    case TLSEXT_cert_type_rpk:
4181
0
        if (!tls_output_rpk(s, pkt, cpk)) {
4182
            /* SSLfatal() already called */
4183
0
            return 0;
4184
0
        }
4185
0
        break;
4186
15.7k
    case TLSEXT_cert_type_x509:
4187
15.7k
        if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {
4188
            /* SSLfatal() already called */
4189
0
            return 0;
4190
0
        }
4191
15.7k
        break;
4192
15.7k
    default:
4193
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4194
0
        return 0;
4195
15.7k
    }
4196
4197
15.7k
    return CON_FUNC_SUCCESS;
4198
15.7k
}
4199
4200
#ifndef OPENSSL_NO_COMP_ALG
4201
CON_FUNC_RETURN tls_construct_server_compressed_certificate(SSL_CONNECTION *sc, WPACKET *pkt)
4202
{
4203
    int alg = get_compressed_certificate_alg(sc);
4204
    OSSL_COMP_CERT *cc = sc->s3.tmp.cert->comp_cert[alg];
4205
4206
    if (!ossl_assert(cc != NULL)) {
4207
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4208
        return 0;
4209
    }
4210
    /*
4211
     * Server can't compress on-demand
4212
     * Use pre-compressed certificate
4213
     */
4214
    if (!WPACKET_put_bytes_u16(pkt, alg)
4215
        || !WPACKET_put_bytes_u24(pkt, cc->orig_len)
4216
        || !WPACKET_start_sub_packet_u24(pkt)
4217
        || !WPACKET_memcpy(pkt, cc->data, cc->len)
4218
        || !WPACKET_close(pkt)) {
4219
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4220
        return 0;
4221
    }
4222
4223
    sc->s3.tmp.cert->cert_comp_used++;
4224
    return 1;
4225
}
4226
#endif
4227
4228
static int create_ticket_prequel(SSL_CONNECTION *s, WPACKET *pkt,
4229
    uint32_t age_add, unsigned char *tick_nonce)
4230
93
{
4231
93
    uint32_t timeout = (uint32_t)ossl_time2seconds(s->session->timeout);
4232
4233
    /*
4234
     * Ticket lifetime hint:
4235
     * In TLSv1.3 we reset the "time" field above, and always specify the
4236
     * timeout, limited to a 1 week period per RFC8446.
4237
     * For TLSv1.2 this is advisory only and we leave this unspecified for
4238
     * resumed session (for simplicity).
4239
     */
4240
93
#define ONE_WEEK_SEC (7 * 24 * 60 * 60)
4241
4242
93
    if (SSL_CONNECTION_IS_TLS13(s)) {
4243
0
        if (ossl_time_compare(s->session->timeout,
4244
0
                ossl_seconds2time(ONE_WEEK_SEC))
4245
0
            > 0)
4246
0
            timeout = ONE_WEEK_SEC;
4247
93
    } else if (s->hit)
4248
0
        timeout = 0;
4249
4250
93
    if (!WPACKET_put_bytes_u32(pkt, timeout)) {
4251
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4252
0
        return 0;
4253
0
    }
4254
4255
93
    if (SSL_CONNECTION_IS_TLS13(s)) {
4256
0
        if (!WPACKET_put_bytes_u32(pkt, age_add)
4257
0
            || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
4258
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4259
0
            return 0;
4260
0
        }
4261
0
    }
4262
4263
    /* Start the sub-packet for the actual ticket data */
4264
93
    if (!WPACKET_start_sub_packet_u16(pkt)) {
4265
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4266
0
        return 0;
4267
0
    }
4268
4269
93
    return 1;
4270
93
}
4271
4272
static CON_FUNC_RETURN construct_stateless_ticket(SSL_CONNECTION *s,
4273
    WPACKET *pkt,
4274
    uint32_t age_add,
4275
    unsigned char *tick_nonce)
4276
93
{
4277
93
    unsigned char *senc = NULL;
4278
93
    EVP_CIPHER_CTX *ctx = NULL;
4279
93
    SSL_HMAC *hctx = NULL;
4280
93
    unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
4281
93
    const unsigned char *const_p;
4282
93
    int len, slen_full, slen, lenfinal;
4283
93
    SSL_SESSION *sess;
4284
93
    size_t hlen;
4285
93
    SSL_CTX *tctx = s->session_ctx;
4286
93
    unsigned char iv[EVP_MAX_IV_LENGTH];
4287
93
    unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
4288
93
    int iv_len;
4289
93
    CON_FUNC_RETURN ok = CON_FUNC_ERROR;
4290
93
    size_t macoffset, macendoffset;
4291
93
    SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
4292
93
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
4293
4294
    /* get session encoding length */
4295
93
    slen_full = i2d_SSL_SESSION(s->session, NULL);
4296
    /*
4297
     * Some length values are 16 bits, so forget it if session is too
4298
     * long
4299
     */
4300
93
    if (slen_full == 0 || slen_full > 0xFF00) {
4301
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4302
0
        goto err;
4303
0
    }
4304
93
    senc = OPENSSL_malloc(slen_full);
4305
93
    if (senc == NULL) {
4306
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4307
0
        goto err;
4308
0
    }
4309
4310
93
    ctx = EVP_CIPHER_CTX_new();
4311
93
    if (ctx == NULL) {
4312
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
4313
0
        goto err;
4314
0
    }
4315
93
    hctx = ssl_hmac_new(tctx);
4316
93
    if (hctx == NULL) {
4317
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
4318
0
        goto err;
4319
0
    }
4320
4321
93
    p = senc;
4322
93
    if (!i2d_SSL_SESSION(s->session, &p)) {
4323
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4324
0
        goto err;
4325
0
    }
4326
4327
    /*
4328
     * create a fresh copy (not shared with other threads) to clean up
4329
     */
4330
93
    const_p = senc;
4331
93
    sess = d2i_SSL_SESSION_ex(NULL, &const_p, slen_full, sctx->libctx,
4332
93
        sctx->propq);
4333
93
    if (sess == NULL) {
4334
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4335
0
        goto err;
4336
0
    }
4337
4338
93
    slen = i2d_SSL_SESSION(sess, NULL);
4339
93
    if (slen == 0 || slen > slen_full) {
4340
        /* shouldn't ever happen */
4341
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4342
0
        SSL_SESSION_free(sess);
4343
0
        goto err;
4344
0
    }
4345
93
    p = senc;
4346
93
    if (!i2d_SSL_SESSION(sess, &p)) {
4347
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4348
0
        SSL_SESSION_free(sess);
4349
0
        goto err;
4350
0
    }
4351
93
    SSL_SESSION_free(sess);
4352
4353
    /*
4354
     * Initialize HMAC and cipher contexts. If callback present it does
4355
     * all the work otherwise use generated values from parent ctx.
4356
     */
4357
93
#ifndef OPENSSL_NO_DEPRECATED_3_0
4358
93
    if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
4359
#else
4360
    if (tctx->ext.ticket_key_evp_cb != NULL)
4361
#endif
4362
0
    {
4363
0
        int ret = 0;
4364
4365
0
        if (tctx->ext.ticket_key_evp_cb != NULL)
4366
0
            ret = tctx->ext.ticket_key_evp_cb(ssl, key_name, iv, ctx,
4367
0
                ssl_hmac_get0_EVP_MAC_CTX(hctx),
4368
0
                1);
4369
0
#ifndef OPENSSL_NO_DEPRECATED_3_0
4370
0
        else if (tctx->ext.ticket_key_cb != NULL)
4371
            /* if 0 is returned, write an empty ticket */
4372
0
            ret = tctx->ext.ticket_key_cb(ssl, key_name, iv, ctx,
4373
0
                ssl_hmac_get0_HMAC_CTX(hctx), 1);
4374
0
#endif
4375
4376
0
        if (ret == 0) {
4377
            /*
4378
             * In TLSv1.2 we construct a 0 length ticket. In TLSv1.3 a 0
4379
             * length ticket is not allowed so we abort construction of the
4380
             * ticket
4381
             */
4382
0
            if (SSL_CONNECTION_IS_TLS13(s)) {
4383
0
                ok = CON_FUNC_DONT_SEND;
4384
0
                goto err;
4385
0
            }
4386
            /* Put timeout and length */
4387
0
            if (!WPACKET_put_bytes_u32(pkt, 0)
4388
0
                || !WPACKET_put_bytes_u16(pkt, 0)) {
4389
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4390
0
                goto err;
4391
0
            }
4392
0
            OPENSSL_free(senc);
4393
0
            EVP_CIPHER_CTX_free(ctx);
4394
0
            ssl_hmac_free(hctx);
4395
0
            return CON_FUNC_SUCCESS;
4396
0
        }
4397
0
        if (ret < 0) {
4398
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
4399
0
            goto err;
4400
0
        }
4401
0
        iv_len = EVP_CIPHER_CTX_get_iv_length(ctx);
4402
0
        if (iv_len < 0) {
4403
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4404
0
            goto err;
4405
0
        }
4406
93
    } else {
4407
93
        EVP_CIPHER *cipher = EVP_CIPHER_fetch(sctx->libctx, "AES-256-CBC",
4408
93
            sctx->propq);
4409
4410
93
        if (cipher == NULL) {
4411
            /* Error is already recorded */
4412
0
            SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
4413
0
            goto err;
4414
0
        }
4415
4416
93
        iv_len = EVP_CIPHER_get_iv_length(cipher);
4417
93
        if (iv_len < 0
4418
93
            || RAND_bytes_ex(sctx->libctx, iv, iv_len, 0) <= 0
4419
93
            || !EVP_EncryptInit_ex(ctx, cipher, NULL,
4420
93
                tctx->ext.secure->tick_aes_key, iv)
4421
93
            || !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
4422
93
                sizeof(tctx->ext.secure->tick_hmac_key),
4423
93
                "SHA256")) {
4424
0
            EVP_CIPHER_free(cipher);
4425
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4426
0
            goto err;
4427
0
        }
4428
93
        EVP_CIPHER_free(cipher);
4429
93
        memcpy(key_name, tctx->ext.tick_key_name,
4430
93
            sizeof(tctx->ext.tick_key_name));
4431
93
    }
4432
4433
93
    if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4434
        /* SSLfatal() already called */
4435
0
        goto err;
4436
0
    }
4437
4438
93
    if (!WPACKET_get_total_written(pkt, &macoffset)
4439
        /* Output key name */
4440
93
        || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
4441
        /* output IV */
4442
93
        || !WPACKET_memcpy(pkt, iv, iv_len)
4443
93
        || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
4444
93
            &encdata1)
4445
        /* Encrypt session data */
4446
93
        || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
4447
93
        || !WPACKET_allocate_bytes(pkt, len, &encdata2)
4448
93
        || encdata1 != encdata2
4449
93
        || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
4450
93
        || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
4451
93
        || encdata1 + len != encdata2
4452
93
        || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
4453
93
        || !WPACKET_get_total_written(pkt, &macendoffset)
4454
93
        || !ssl_hmac_update(hctx,
4455
93
            (unsigned char *)s->init_buf->data + macoffset,
4456
93
            macendoffset - macoffset)
4457
93
        || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
4458
93
        || !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)
4459
93
        || hlen > EVP_MAX_MD_SIZE
4460
93
        || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
4461
93
        || macdata1 != macdata2) {
4462
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4463
0
        goto err;
4464
0
    }
4465
4466
    /* Close the sub-packet created by create_ticket_prequel() */
4467
93
    if (!WPACKET_close(pkt)) {
4468
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4469
0
        goto err;
4470
0
    }
4471
4472
93
    ok = CON_FUNC_SUCCESS;
4473
93
err:
4474
93
    OPENSSL_free(senc);
4475
93
    EVP_CIPHER_CTX_free(ctx);
4476
93
    ssl_hmac_free(hctx);
4477
93
    return ok;
4478
93
}
4479
4480
static int construct_stateful_ticket(SSL_CONNECTION *s, WPACKET *pkt,
4481
    uint32_t age_add,
4482
    unsigned char *tick_nonce)
4483
0
{
4484
0
    if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4485
        /* SSLfatal() already called */
4486
0
        return 0;
4487
0
    }
4488
4489
0
    if (!WPACKET_memcpy(pkt, s->session->session_id,
4490
0
            s->session->session_id_length)
4491
0
        || !WPACKET_close(pkt)) {
4492
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4493
0
        return 0;
4494
0
    }
4495
4496
0
    return 1;
4497
0
}
4498
4499
static void tls_update_ticket_counts(SSL_CONNECTION *s)
4500
0
{
4501
    /*
4502
     * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
4503
     * gets reset to 0 if we send more tickets following a post-handshake
4504
     * auth, but |next_ticket_nonce| does not.  If we're sending extra
4505
     * tickets, decrement the count of pending extra tickets.
4506
     */
4507
0
    s->sent_tickets++;
4508
0
    s->next_ticket_nonce++;
4509
0
    if (s->ext.extra_tickets_expected > 0)
4510
0
        s->ext.extra_tickets_expected--;
4511
0
}
4512
4513
CON_FUNC_RETURN tls_construct_new_session_ticket(SSL_CONNECTION *s, WPACKET *pkt)
4514
93
{
4515
93
    SSL_CTX *tctx = s->session_ctx;
4516
93
    unsigned char tick_nonce[TICKET_NONCE_SIZE];
4517
93
    union {
4518
93
        unsigned char age_add_c[sizeof(uint32_t)];
4519
93
        uint32_t age_add;
4520
93
    } age_add_u;
4521
93
    CON_FUNC_RETURN ret = CON_FUNC_ERROR;
4522
4523
93
    age_add_u.age_add = 0;
4524
4525
93
    if (SSL_CONNECTION_IS_TLS13(s)) {
4526
0
        size_t i, hashlen;
4527
0
        uint64_t nonce;
4528
        /* ASCII: "resumption", in hex for EBCDIC compatibility */
4529
0
        static const unsigned char nonce_label[] = { 0x72, 0x65, 0x73, 0x75, 0x6D,
4530
0
            0x70, 0x74, 0x69, 0x6F, 0x6E };
4531
0
        const EVP_MD *md = ssl_handshake_md(s);
4532
0
        int hashleni = EVP_MD_get_size(md);
4533
4534
        /* Ensure cast to size_t is safe */
4535
0
        if (!ossl_assert(hashleni > 0)) {
4536
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4537
0
            goto err;
4538
0
        }
4539
0
        hashlen = (size_t)hashleni;
4540
4541
        /*
4542
         * If we already sent one NewSessionTicket, or we resumed then
4543
         * s->session may already be in a cache and so we must not modify it.
4544
         * Instead we need to take a copy of it and modify that.
4545
         */
4546
0
        if (s->sent_tickets != 0 || s->hit) {
4547
0
            SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
4548
4549
0
            if (new_sess == NULL) {
4550
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
4551
0
                goto err;
4552
0
            }
4553
4554
0
            SSL_SESSION_free(s->session);
4555
0
            s->session = new_sess;
4556
0
        }
4557
4558
0
        if (!ssl_generate_session_id(s, s->session)) {
4559
            /* SSLfatal() already called */
4560
0
            goto err;
4561
0
        }
4562
0
        if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
4563
0
                age_add_u.age_add_c, sizeof(age_add_u), 0)
4564
0
            <= 0) {
4565
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4566
0
            goto err;
4567
0
        }
4568
0
        s->session->ext.tick_age_add = age_add_u.age_add;
4569
4570
0
        nonce = s->next_ticket_nonce;
4571
0
        for (i = TICKET_NONCE_SIZE; i > 0; i--) {
4572
0
            tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
4573
0
            nonce >>= 8;
4574
0
        }
4575
4576
0
        if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
4577
0
                nonce_label,
4578
0
                sizeof(nonce_label),
4579
0
                tick_nonce,
4580
0
                TICKET_NONCE_SIZE,
4581
0
                s->session->master_key,
4582
0
                hashlen, 1)) {
4583
            /* SSLfatal() already called */
4584
0
            goto err;
4585
0
        }
4586
0
        s->session->master_key_length = hashlen;
4587
4588
0
        s->session->time = ossl_time_now();
4589
0
        ssl_session_calculate_timeout(s->session);
4590
0
        if (s->s3.alpn_selected != NULL) {
4591
0
            OPENSSL_free(s->session->ext.alpn_selected);
4592
0
            s->session->ext.alpn_selected = OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
4593
0
            if (s->session->ext.alpn_selected == NULL) {
4594
0
                s->session->ext.alpn_selected_len = 0;
4595
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4596
0
                goto err;
4597
0
            }
4598
0
            s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
4599
0
        }
4600
0
        s->session->ext.max_early_data = s->max_early_data;
4601
0
    }
4602
4603
93
    if (tctx->generate_ticket_cb != NULL && tctx->generate_ticket_cb(SSL_CONNECTION_GET_USER_SSL(s), tctx->ticket_cb_data) == 0) {
4604
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4605
0
        goto err;
4606
0
    }
4607
    /*
4608
     * If we are using anti-replay protection then we behave as if
4609
     * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
4610
     * is no point in using full stateless tickets.
4611
     */
4612
93
    if (SSL_CONNECTION_IS_TLS13(s)
4613
0
        && ((s->options & SSL_OP_NO_TICKET) != 0
4614
0
            || (s->max_early_data > 0
4615
0
                && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
4616
0
        if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
4617
            /* SSLfatal() already called */
4618
0
            goto err;
4619
0
        }
4620
93
    } else {
4621
93
        CON_FUNC_RETURN tmpret;
4622
4623
93
        tmpret = construct_stateless_ticket(s, pkt, age_add_u.age_add,
4624
93
            tick_nonce);
4625
93
        if (tmpret != CON_FUNC_SUCCESS) {
4626
0
            if (tmpret == CON_FUNC_DONT_SEND) {
4627
                /* Non-fatal. Abort construction but continue */
4628
0
                ret = CON_FUNC_DONT_SEND;
4629
                /* We count this as a success so update the counts anwyay */
4630
0
                tls_update_ticket_counts(s);
4631
0
            }
4632
            /* else SSLfatal() already called */
4633
0
            goto err;
4634
0
        }
4635
93
    }
4636
4637
93
    if (SSL_CONNECTION_IS_TLS13(s)) {
4638
0
        if (!tls_construct_extensions(s, pkt,
4639
0
                SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
4640
0
                NULL, 0)) {
4641
            /* SSLfatal() already called */
4642
0
            goto err;
4643
0
        }
4644
0
        tls_update_ticket_counts(s);
4645
0
        ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
4646
0
    }
4647
4648
93
    ret = CON_FUNC_SUCCESS;
4649
93
err:
4650
93
    return ret;
4651
93
}
4652
4653
/*
4654
 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
4655
 * create a separate message. Returns 1 on success or 0 on failure.
4656
 */
4657
int tls_construct_cert_status_body(SSL_CONNECTION *s, OCSP_RESPONSE *resp, WPACKET *pkt)
4658
0
{
4659
0
    unsigned char *respder = NULL;
4660
0
    int resplen = 0;
4661
4662
0
    if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)) {
4663
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4664
0
        return 0;
4665
0
    }
4666
4667
0
#ifndef OPENSSL_NO_OCSP
4668
0
    resplen = i2d_OCSP_RESPONSE(resp, &respder);
4669
0
#endif
4670
4671
0
    if (!WPACKET_sub_memcpy_u24(pkt, respder, resplen)) {
4672
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4673
0
        OPENSSL_free(respder);
4674
0
        return 0;
4675
0
    }
4676
4677
0
    OPENSSL_free(respder);
4678
0
    return 1;
4679
0
}
4680
4681
CON_FUNC_RETURN tls_construct_cert_status(SSL_CONNECTION *s, WPACKET *pkt)
4682
0
{
4683
0
    OCSP_RESPONSE *resp;
4684
4685
0
    resp = ossl_get_ocsp_response(s, 0);
4686
4687
0
    if (resp == NULL)
4688
0
        return CON_FUNC_DONT_SEND;
4689
4690
0
    if (!tls_construct_cert_status_body(s, resp, pkt)) {
4691
        /* SSLfatal() already called */
4692
0
        return CON_FUNC_ERROR;
4693
0
    }
4694
4695
0
    return CON_FUNC_SUCCESS;
4696
0
}
4697
4698
#ifndef OPENSSL_NO_NEXTPROTONEG
4699
/*
4700
 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
4701
 * It sets the next_proto member in s if found
4702
 */
4703
MSG_PROCESS_RETURN tls_process_next_proto(SSL_CONNECTION *s, PACKET *pkt)
4704
0
{
4705
0
    PACKET next_proto, padding;
4706
0
    size_t next_proto_len;
4707
4708
    /*-
4709
     * The payload looks like:
4710
     *   uint8 proto_len;
4711
     *   uint8 proto[proto_len];
4712
     *   uint8 padding_len;
4713
     *   uint8 padding[padding_len];
4714
     */
4715
0
    if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
4716
0
        || !PACKET_get_length_prefixed_1(pkt, &padding)
4717
0
        || PACKET_remaining(pkt) > 0) {
4718
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4719
0
        return MSG_PROCESS_ERROR;
4720
0
    }
4721
4722
0
    if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
4723
0
        s->ext.npn_len = 0;
4724
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4725
0
        return MSG_PROCESS_ERROR;
4726
0
    }
4727
4728
0
    s->ext.npn_len = (unsigned char)next_proto_len;
4729
4730
0
    return MSG_PROCESS_CONTINUE_READING;
4731
0
}
4732
#endif
4733
4734
static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,
4735
    WPACKET *pkt)
4736
2.33k
{
4737
2.33k
    if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4738
2.33k
            NULL, 0)) {
4739
        /* SSLfatal() already called */
4740
0
        return CON_FUNC_ERROR;
4741
0
    }
4742
4743
2.33k
    return CON_FUNC_SUCCESS;
4744
2.33k
}
4745
4746
MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL_CONNECTION *s, PACKET *pkt)
4747
0
{
4748
0
    if (PACKET_remaining(pkt) != 0) {
4749
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4750
0
        return MSG_PROCESS_ERROR;
4751
0
    }
4752
4753
0
    if (s->early_data_state != SSL_EARLY_DATA_READING
4754
0
        && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
4755
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4756
0
        return MSG_PROCESS_ERROR;
4757
0
    }
4758
4759
    /*
4760
     * EndOfEarlyData signals a key change so the end of the message must be on
4761
     * a record boundary.
4762
     */
4763
0
    if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
4764
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
4765
0
        return MSG_PROCESS_ERROR;
4766
0
    }
4767
4768
0
    s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
4769
0
    if (!SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->change_cipher_state(s,
4770
0
            SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
4771
        /* SSLfatal() already called */
4772
0
        return MSG_PROCESS_ERROR;
4773
0
    }
4774
4775
0
    return MSG_PROCESS_CONTINUE_READING;
4776
0
}