Coverage Report

Created: 2026-03-09 06:55

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