Coverage Report

Created: 2026-11-16 07:12

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