Coverage Report

Created: 2026-08-31 06:56

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