Coverage Report

Created: 2026-04-22 06:14

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