Coverage Report

Created: 2025-12-31 06:58

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