Coverage Report

Created: 2026-08-18 07:24

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