Coverage Report

Created: 2026-05-24 07:14

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
27.9k
{
56
27.9k
    return sc->session->peer_rpk != NULL || sc->session->peer != NULL;
57
27.9k
}
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
230
{
70
230
    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
230
    switch (st->hand_state) {
78
0
    default:
79
0
        break;
80
81
230
    case TLS_ST_EARLY_DATA:
82
230
        if (s->hello_retry_request == SSL_HRR_PENDING) {
83
227
            if (mt == SSL3_MT_CLIENT_HELLO) {
84
222
                st->hand_state = TLS_ST_SR_CLNT_HELLO;
85
222
                return 1;
86
222
            }
87
5
            break;
88
227
        } 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
230
    }
170
171
    /* No valid transition found */
172
8
    return 0;
173
230
}
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
89.7k
{
186
89.7k
    OSSL_STATEM *st = &s->statem;
187
188
89.7k
    if (SSL_CONNECTION_IS_TLS13(s)) {
189
252
        if (!ossl_statem_server13_read_transition(s, mt))
190
13
            goto err;
191
239
        return 1;
192
252
    }
193
194
89.4k
    switch (st->hand_state) {
195
0
    default:
196
0
        break;
197
198
32.5k
    case TLS_ST_BEFORE:
199
64.0k
    case TLS_ST_OK:
200
64.0k
    case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
201
64.0k
        if (mt == SSL3_MT_CLIENT_HELLO) {
202
63.6k
            st->hand_state = TLS_ST_SR_CLNT_HELLO;
203
63.6k
            return 1;
204
63.6k
        }
205
428
        break;
206
207
14.6k
    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
14.6k
        if (mt == SSL3_MT_CLIENT_KEY_EXCHANGE) {
219
14.4k
            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
14.4k
            } else {
236
14.4k
                st->hand_state = TLS_ST_SR_KEY_EXCH;
237
14.4k
                return 1;
238
14.4k
            }
239
14.4k
        } 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
167
        break;
246
247
167
    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
9.20k
    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
9.20k
        if (!received_client_cert(s) || st->no_cert_verify) {
264
9.20k
            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.77k
                st->hand_state = TLS_ST_SR_CHANGE;
272
8.77k
                return 1;
273
8.77k
            }
274
9.20k
        } 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
429
        break;
281
282
429
    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.50k
    case TLS_ST_SR_CHANGE:
290
1.50k
#ifndef OPENSSL_NO_NEXTPROTONEG
291
1.50k
        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.50k
        } else {
297
1.50k
#endif
298
1.50k
            if (mt == SSL3_MT_FINISHED) {
299
1.23k
                st->hand_state = TLS_ST_SR_FINISHED;
300
1.23k
                return 1;
301
1.23k
            }
302
1.50k
#ifndef OPENSSL_NO_NEXTPROTONEG
303
1.50k
        }
304
271
#endif
305
271
        break;
306
307
271
#ifndef OPENSSL_NO_NEXTPROTONEG
308
271
    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
77
    case TLS_ST_SW_FINISHED:
317
77
        if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
318
65
            st->hand_state = TLS_ST_SR_CHANGE;
319
65
            return 1;
320
65
        }
321
12
        break;
322
89.4k
    }
323
324
1.32k
err:
325
    /* No valid transition found */
326
1.32k
    if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
327
21
        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
21
        s->init_num = 0;
334
21
        s->rwstate = SSL_READING;
335
21
        rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));
336
21
        BIO_clear_retry_flags(rbio);
337
21
        BIO_set_retry_read(rbio);
338
21
        return 0;
339
21
    }
340
1.32k
    SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
341
1.29k
    return 0;
342
1.32k
}
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.5k
{
353
26.5k
    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.5k
    if (alg_k & (SSL_kDHE | SSL_kECDHE)
364
    /*
365
     * PSK: send ServerKeyExchange if PSK identity hint if
366
     * provided
367
     */
368
13.8k
#ifndef OPENSSL_NO_PSK
369
        /* Only send SKE if we have identity hint for plain PSK */
370
13.8k
        || ((alg_k & (SSL_kPSK | SSL_kRSAPSK))
371
0
            && s->cert->psk_identity_hint)
372
        /* For other PSK always send SKE */
373
13.8k
        || (alg_k & (SSL_PSK & (SSL_kDHEPSK | SSL_kECDHEPSK)))
374
13.8k
#endif
375
13.8k
#ifndef OPENSSL_NO_SRP
376
        /* SRP: send ServerKeyExchange */
377
13.8k
        || (alg_k & SSL_kSRP)
378
26.5k
#endif
379
26.5k
    ) {
380
12.7k
        return 1;
381
12.7k
    }
382
383
13.8k
    return 0;
384
26.5k
}
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.45k
{
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.45k
    return TLSEXT_comp_cert_none;
405
2.45k
}
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.9k
{
416
31.9k
    if (
417
        /* don't request cert unless asked for it: */
418
31.9k
        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.9k
    return 0;
454
31.9k
}
455
456
static int do_compressed_cert(SSL_CONNECTION *sc)
457
2.45k
{
458
    /* If we negotiated RPK, we won't attempt to compress it */
459
2.45k
    return sc->ext.server_cert_type == TLSEXT_cert_type_x509
460
2.45k
        && get_compressed_certificate_alg(sc) != TLSEXT_comp_cert_none;
461
2.45k
}
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
16.5k
{
470
16.5k
    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
16.5k
    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
2.29k
    case TLS_ST_SR_CLNT_HELLO:
500
2.29k
        st->hand_state = TLS_ST_SW_SRVR_HELLO;
501
2.29k
        return WRITE_TRAN_CONTINUE;
502
503
2.28k
    case TLS_ST_SW_SRVR_HELLO:
504
2.28k
        if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
505
2.28k
            && s->hello_retry_request != SSL_HRR_COMPLETE)
506
2.24k
            st->hand_state = TLS_ST_SW_CHANGE;
507
41
        else if (s->hello_retry_request == SSL_HRR_PENDING)
508
0
            st->hand_state = TLS_ST_EARLY_DATA;
509
41
        else
510
41
            st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
511
2.28k
        return WRITE_TRAN_CONTINUE;
512
513
2.24k
    case TLS_ST_SW_CHANGE:
514
2.24k
        if (s->hello_retry_request == SSL_HRR_PENDING)
515
427
            st->hand_state = TLS_ST_EARLY_DATA;
516
1.82k
        else
517
1.82k
            st->hand_state = TLS_ST_SW_ENCRYPTED_EXTENSIONS;
518
2.24k
        return WRITE_TRAN_CONTINUE;
519
520
1.86k
    case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
521
1.86k
        if (s->hit)
522
0
            st->hand_state = TLS_ST_SW_FINISHED;
523
1.86k
        else if (send_certificate_request(s))
524
0
            st->hand_state = TLS_ST_SW_CERT_REQ;
525
1.86k
        else if (do_compressed_cert(s))
526
0
            st->hand_state = TLS_ST_SW_COMP_CERT;
527
1.86k
        else
528
1.86k
            st->hand_state = TLS_ST_SW_CERT;
529
530
1.86k
        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
1.86k
    case TLS_ST_SW_CERT:
545
1.86k
        st->hand_state = TLS_ST_SW_CERT_VRFY;
546
1.86k
        return WRITE_TRAN_CONTINUE;
547
548
1.86k
    case TLS_ST_SW_CERT_VRFY:
549
1.86k
        st->hand_state = TLS_ST_SW_FINISHED;
550
1.86k
        return WRITE_TRAN_CONTINUE;
551
552
1.86k
    case TLS_ST_SW_FINISHED:
553
1.86k
        st->hand_state = TLS_ST_EARLY_DATA;
554
1.86k
        s->ts_msg_write = ossl_time_now();
555
1.86k
        return WRITE_TRAN_CONTINUE;
556
557
2.28k
    case TLS_ST_EARLY_DATA:
558
2.28k
        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
16.5k
    }
601
16.5k
}
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
323k
{
609
323k
    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
323k
    if (SSL_CONNECTION_IS_TLS13(s))
617
26.5k
        return ossl_statem_server13_write_transition(s);
618
619
296k
    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
61.5k
    case TLS_ST_OK:
626
61.5k
        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
61.5k
        if (!tls_setup_handshake(s)) {
634
            /* SSLfatal() already called */
635
0
            return WRITE_TRAN_ERROR;
636
0
        }
637
        /* Fall through */
638
639
113k
    case TLS_ST_BEFORE:
640
        /* Just go straight to trying to read from the client */
641
113k
        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
87.6k
    case TLS_ST_SR_CLNT_HELLO:
648
87.6k
        if (SSL_CONNECTION_IS_DTLS(s) && !s->d1->cookie_verified
649
13.1k
            && (SSL_get_options(SSL_CONNECTION_GET_SSL(s)) & SSL_OP_COOKIE_EXCHANGE)) {
650
0
            st->hand_state = DTLS_ST_SW_HELLO_VERIFY_REQUEST;
651
87.6k
        } else if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
652
            /* We must have rejected the renegotiation */
653
60.8k
            st->hand_state = TLS_ST_OK;
654
60.8k
            return WRITE_TRAN_CONTINUE;
655
60.8k
        } else {
656
26.7k
            st->hand_state = TLS_ST_SW_SRVR_HELLO;
657
26.7k
        }
658
26.7k
        return WRITE_TRAN_CONTINUE;
659
660
0
    case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
661
0
        return WRITE_TRAN_FINISHED;
662
663
26.7k
    case TLS_ST_SW_SRVR_HELLO:
664
26.7k
        if (s->hit) {
665
202
            if (s->ext.ticket_expected)
666
0
                st->hand_state = TLS_ST_SW_SESSION_TICKET;
667
202
            else
668
202
                st->hand_state = TLS_ST_SW_CHANGE;
669
26.5k
        } else {
670
            /* Check if it is anon DH or anon ECDH, */
671
            /* normal PSK or SRP */
672
26.5k
            if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
673
24.1k
                st->hand_state = TLS_ST_SW_CERT;
674
24.1k
            } else if (send_server_key_exchange(s)) {
675
2.45k
                st->hand_state = TLS_ST_SW_KEY_EXCH;
676
2.45k
            } 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.5k
        }
682
26.7k
        return WRITE_TRAN_CONTINUE;
683
684
24.1k
    case TLS_ST_SW_CERT:
685
24.1k
        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
24.1k
    case TLS_ST_SW_CERT_STATUS:
692
24.1k
        if (send_server_key_exchange(s)) {
693
10.2k
            st->hand_state = TLS_ST_SW_KEY_EXCH;
694
10.2k
            return WRITE_TRAN_CONTINUE;
695
10.2k
        }
696
        /* Fall through */
697
698
26.5k
    case TLS_ST_SW_KEY_EXCH:
699
26.5k
        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.5k
    case TLS_ST_SW_CERT_REQ:
706
26.5k
        st->hand_state = TLS_ST_SW_SRVR_DONE;
707
26.5k
        return WRITE_TRAN_CONTINUE;
708
709
26.5k
    case TLS_ST_SW_SRVR_DONE:
710
26.5k
        s->ts_msg_write = ossl_time_now();
711
26.5k
        return WRITE_TRAN_FINISHED;
712
713
1.57k
    case TLS_ST_SR_FINISHED:
714
1.57k
        s->ts_msg_read = ossl_time_now();
715
1.57k
        if (s->hit) {
716
0
            st->hand_state = TLS_ST_OK;
717
0
            return WRITE_TRAN_CONTINUE;
718
1.57k
        } else if (s->ext.ticket_expected) {
719
97
            st->hand_state = TLS_ST_SW_SESSION_TICKET;
720
1.47k
        } else {
721
1.47k
            st->hand_state = TLS_ST_SW_CHANGE;
722
1.47k
        }
723
1.57k
        return WRITE_TRAN_CONTINUE;
724
725
97
    case TLS_ST_SW_SESSION_TICKET:
726
97
        st->hand_state = TLS_ST_SW_CHANGE;
727
97
        return WRITE_TRAN_CONTINUE;
728
729
1.77k
    case TLS_ST_SW_CHANGE:
730
1.77k
        st->hand_state = TLS_ST_SW_FINISHED;
731
1.77k
        return WRITE_TRAN_CONTINUE;
732
733
1.77k
    case TLS_ST_SW_FINISHED:
734
1.77k
        if (s->hit) {
735
202
            return WRITE_TRAN_FINISHED;
736
202
        }
737
1.57k
        st->hand_state = TLS_ST_OK;
738
1.57k
        return WRITE_TRAN_CONTINUE;
739
296k
    }
740
296k
}
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
123k
{
748
123k
    OSSL_STATEM *st = &s->statem;
749
123k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
750
751
123k
    switch (st->hand_state) {
752
27.3k
    default:
753
        /* No pre work to be done */
754
27.3k
        break;
755
756
27.3k
    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.4k
    case TLS_ST_SW_SRVR_HELLO:
772
16.4k
        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.63k
            st->use_timer = 1;
778
7.63k
        }
779
16.4k
        break;
780
781
14.4k
    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.4k
        return WORK_FINISHED_CONTINUE;
789
790
76
    case TLS_ST_SW_SESSION_TICKET:
791
76
        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
76
        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
76
        break;
810
811
2.96k
    case TLS_ST_SW_CHANGE:
812
2.96k
        if (SSL_CONNECTION_IS_TLS13(s))
813
1.83k
            break;
814
        /* Writes to s->session are only safe for initial handshakes */
815
1.12k
        if (s->session->cipher == NULL) {
816
0
            s->session->cipher = s->s3.tmp.new_cipher;
817
1.12k
        } 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.12k
        if (!ssl->method->ssl3_enc->setup_key_block(s)) {
822
            /* SSLfatal() already called */
823
0
            return WORK_ERROR;
824
0
        }
825
1.12k
        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.12k
        return WORK_FINISHED_CONTINUE;
835
836
1.89k
    case TLS_ST_EARLY_DATA:
837
1.89k
        if (s->early_data_state != SSL_EARLY_DATA_ACCEPTING
838
1.18k
            && (s->s3.flags & TLS1_FLAGS_STATELESS) == 0)
839
1.18k
            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
711
        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
61.3k
    case TLS_ST_OK:
857
        /* Calls SSLfatal() as required */
858
61.3k
        return tls_finish_handshake(s, wst, 1, 1);
859
123k
    }
860
861
45.7k
    return WORK_FINISHED_CONTINUE;
862
123k
}
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
62.4k
{
890
62.4k
    OSSL_STATEM *st = &s->statem;
891
62.4k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
892
893
62.4k
    s->init_num = 0;
894
895
62.4k
    switch (st->hand_state) {
896
24.3k
    default:
897
        /* No post work to be done */
898
24.3k
        break;
899
900
24.3k
    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.4k
    case TLS_ST_SW_SRVR_HELLO:
925
16.4k
        if (SSL_CONNECTION_IS_TLS13(s)
926
1.89k
            && s->hello_retry_request == SSL_HRR_PENDING) {
927
370
            if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0
928
0
                && statem_flush(s) != 1)
929
0
                return WORK_MORE_A;
930
370
            break;
931
370
        }
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
16.0k
        if (!SSL_CONNECTION_IS_TLS13(s)
964
1.52k
            || ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
965
1.52k
                && s->hello_retry_request != SSL_HRR_COMPLETE))
966
16.0k
            break;
967
        /* Fall through */
968
969
3.01k
    case TLS_ST_SW_CHANGE:
970
3.01k
        if (s->hello_retry_request == SSL_HRR_PENDING) {
971
370
            if (!statem_flush(s))
972
0
                return WORK_MORE_A;
973
370
            break;
974
370
        }
975
976
2.64k
        if (SSL_CONNECTION_IS_TLS13(s)) {
977
1.52k
            if (!ssl->method->ssl3_enc->setup_key_block(s)
978
1.52k
                || !tls13_store_handshake_traffic_hash(s)
979
1.52k
                || !ssl->method->ssl3_enc->change_cipher_state(s,
980
1.52k
                    SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
981
                /* SSLfatal() already called */
982
0
                return WORK_ERROR;
983
0
            }
984
985
1.52k
            if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED
986
1.52k
                && !ssl->method->ssl3_enc->change_cipher_state(s,
987
1.52k
                    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.52k
            if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
997
1.52k
                s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 1);
998
1.52k
            break;
999
1.52k
        }
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.12k
        if (!ssl->method->ssl3_enc->change_cipher_state(s,
1012
1.12k
                SSL3_CHANGE_CIPHER_SERVER_WRITE)) {
1013
            /* SSLfatal() already called */
1014
0
            return WORK_ERROR;
1015
0
        }
1016
1.12k
        break;
1017
1018
14.4k
    case TLS_ST_SW_SRVR_DONE:
1019
14.4k
        if (statem_flush(s) != 1)
1020
0
            return WORK_MORE_A;
1021
14.4k
        break;
1022
1023
14.4k
    case TLS_ST_SW_FINISHED:
1024
2.64k
        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.64k
        if (SSL_CONNECTION_IS_TLS13(s)) {
1037
            /* TLS 1.3 gets the secret size from the handshake md */
1038
1.52k
            size_t dummy;
1039
1.52k
            if (!ssl->method->ssl3_enc->generate_master_secret(s,
1040
1.52k
                    s->master_secret, s->handshake_secret, 0,
1041
1.52k
                    &dummy)
1042
1.52k
                || !tls13_store_server_finished_hash(s)
1043
1.52k
                || !ssl->method->ssl3_enc->change_cipher_state(s,
1044
1.52k
                    SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_SERVER_WRITE))
1045
                /* SSLfatal() already called */
1046
0
                return WORK_ERROR;
1047
1.52k
        }
1048
2.64k
        break;
1049
1050
2.64k
    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.52k
    case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1062
1.52k
        if (!s->hit && !send_certificate_request(s)) {
1063
1.52k
            if (!SSL_CONNECTION_IS_TLS13(s)
1064
1.52k
                || (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
1065
0
                s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
1066
1.52k
        }
1067
1.52k
        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
76
    case TLS_ST_SW_SESSION_TICKET:
1079
76
        clear_sys_error();
1080
76
        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
76
        break;
1097
62.4k
    }
1098
1099
62.4k
    return WORK_FINISHED_CONTINUE;
1100
62.4k
}
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
115k
{
1113
115k
    OSSL_STATEM *st = &s->statem;
1114
1115
115k
    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.36k
    case TLS_ST_SW_CHANGE:
1122
5.36k
        if (SSL_CONNECTION_IS_DTLS(s))
1123
0
            *confunc = dtls_construct_change_cipher_spec;
1124
5.36k
        else
1125
5.36k
            *confunc = tls_construct_change_cipher_spec;
1126
5.36k
        *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
1127
5.36k
        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
30.4k
    case TLS_ST_SW_SRVR_HELLO:
1141
30.4k
        *confunc = tls_construct_server_hello;
1142
30.4k
        *mt = SSL3_MT_SERVER_HELLO;
1143
30.4k
        break;
1144
1145
27.0k
    case TLS_ST_SW_CERT:
1146
27.0k
        *confunc = tls_construct_server_certificate;
1147
27.0k
        *mt = SSL3_MT_CERTIFICATE;
1148
27.0k
        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.95k
    case TLS_ST_SW_CERT_VRFY:
1158
2.95k
        *confunc = tls_construct_cert_verify;
1159
2.95k
        *mt = SSL3_MT_CERTIFICATE_VERIFY;
1160
2.95k
        break;
1161
1162
12.7k
    case TLS_ST_SW_KEY_EXCH:
1163
12.7k
        *confunc = tls_construct_server_key_exchange;
1164
12.7k
        *mt = SSL3_MT_SERVER_KEY_EXCHANGE;
1165
12.7k
        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.5k
    case TLS_ST_SW_SRVR_DONE:
1173
26.5k
        *confunc = tls_construct_server_done;
1174
26.5k
        *mt = SSL3_MT_SERVER_DONE;
1175
26.5k
        break;
1176
1177
97
    case TLS_ST_SW_SESSION_TICKET:
1178
97
        *confunc = tls_construct_new_session_ticket;
1179
97
        *mt = SSL3_MT_NEWSESSION_TICKET;
1180
97
        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.73k
    case TLS_ST_SW_FINISHED:
1188
4.73k
        *confunc = tls_construct_finished;
1189
4.73k
        *mt = SSL3_MT_FINISHED;
1190
4.73k
        break;
1191
1192
2.20k
    case TLS_ST_EARLY_DATA:
1193
2.20k
        *confunc = NULL;
1194
2.20k
        *mt = SSL3_MT_DUMMY;
1195
2.20k
        break;
1196
1197
2.95k
    case TLS_ST_SW_ENCRYPTED_EXTENSIONS:
1198
2.95k
        *confunc = tls_construct_encrypted_extensions;
1199
2.95k
        *mt = SSL3_MT_ENCRYPTED_EXTENSIONS;
1200
2.95k
        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
115k
    }
1207
1208
115k
    return 1;
1209
115k
}
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
101k
#define CLIENT_HELLO_MAX_LENGTH 131396
1227
1228
18.2k
#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
133k
{
1237
133k
    OSSL_STATEM *st = &s->statem;
1238
1239
133k
    switch (st->hand_state) {
1240
0
    default:
1241
        /* Shouldn't happen */
1242
0
        return 0;
1243
1244
101k
    case TLS_ST_SR_CLNT_HELLO:
1245
101k
        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
18.2k
    case TLS_ST_SR_KEY_EXCH:
1255
18.2k
        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
11.2k
    case TLS_ST_SR_CHANGE:
1266
11.2k
        return CCS_MAX_LENGTH;
1267
1268
1.65k
    case TLS_ST_SR_FINISHED:
1269
1.65k
        return FINISHED_MAX_LENGTH;
1270
1271
0
    case TLS_ST_SR_KEY_UPDATE:
1272
0
        return KEY_UPDATE_MAX_LENGTH;
1273
133k
    }
1274
133k
}
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
138k
{
1282
138k
    OSSL_STATEM *st = &s->statem;
1283
1284
138k
    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
105k
    case TLS_ST_SR_CLNT_HELLO:
1291
105k
        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.5k
    case TLS_ST_SR_KEY_EXCH:
1305
19.5k
        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.7k
    case TLS_ST_SR_CHANGE:
1316
11.7k
        return tls_process_change_cipher_spec(s, pkt);
1317
1318
1.61k
    case TLS_ST_SR_FINISHED:
1319
1.61k
        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
138k
    }
1324
138k
}
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
60.1k
{
1333
60.1k
    OSSL_STATEM *st = &s->statem;
1334
1335
60.1k
    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.5k
    case TLS_ST_SR_CLNT_HELLO:
1342
42.5k
        return tls_post_process_client_hello(s, wst);
1343
1344
17.6k
    case TLS_ST_SR_KEY_EXCH:
1345
17.6k
        return tls_post_process_client_key_exchange(s, wst);
1346
60.1k
    }
1347
60.1k
}
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
30.4k
{
1353
30.4k
    int ret;
1354
30.4k
    int al = SSL_AD_UNRECOGNIZED_NAME;
1355
1356
30.4k
    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
30.4k
    return 1;
1379
30.4k
}
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
62.2k
    ((options & SSL_OP_NO_RENEGOTIATION) == 0 \
1502
62.2k
        && (options & SSL_OP_ALLOW_CLIENT_RENEGOTIATION) != 0)
1503
1504
MSG_PROCESS_RETURN tls_process_client_hello(SSL_CONNECTION *s, PACKET *pkt)
1505
67.4k
{
1506
    /* |cookie| will only be initialized for DTLS. */
1507
67.4k
    PACKET session_id, compression, extensions, cookie;
1508
67.4k
    static const unsigned char null_compression = 0;
1509
67.4k
    CLIENTHELLO_MSG *clienthello = NULL;
1510
1511
    /* Check if this is actually an unexpected renegotiation ClientHello */
1512
67.4k
    if (s->renegotiate == 0 && !SSL_IS_FIRST_HANDSHAKE(s)) {
1513
31.1k
        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
31.1k
        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
31.1k
                    == 0)) {
1522
31.1k
            ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1523
31.1k
            return MSG_PROCESS_FINISHED_READING;
1524
31.1k
        }
1525
0
        s->renegotiate = 1;
1526
0
        s->new_session = 1;
1527
0
    }
1528
1529
36.3k
    clienthello = OPENSSL_zalloc(sizeof(*clienthello));
1530
36.3k
    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
36.3k
    clienthello->isv2 = RECORD_LAYER_is_sslv2_record(&s->rlayer);
1539
36.3k
    PACKET_null_init(&cookie);
1540
1541
36.3k
    if (clienthello->isv2) {
1542
4.98k
        unsigned int mt;
1543
1544
4.98k
        if (!SSL_IS_FIRST_HANDSHAKE(s)
1545
4.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
4.98k
        if (!PACKET_get_1(pkt, &mt)
1566
4.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
4.98k
    }
1576
1577
36.3k
    if (!PACKET_get_net_2(pkt, &clienthello->legacy_version)) {
1578
81
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
1579
81
        goto err;
1580
81
    }
1581
1582
    /* Parse the message and load client random. */
1583
36.2k
    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
4.98k
        unsigned int ciphersuite_len, session_id_len, challenge_len;
1590
4.98k
        PACKET challenge;
1591
1592
4.98k
        if (!PACKET_get_net_2(pkt, &ciphersuite_len)
1593
4.98k
            || !PACKET_get_net_2(pkt, &session_id_len)
1594
4.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
4.98k
        if (session_id_len > SSL_MAX_SSL_SESSION_ID_LENGTH) {
1600
109
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_MISMATCH);
1601
109
            goto err;
1602
109
        }
1603
1604
4.87k
        if (!PACKET_get_sub_packet(pkt, &clienthello->ciphersuites,
1605
4.87k
                ciphersuite_len)
1606
4.81k
            || !PACKET_copy_bytes(pkt, clienthello->session_id, session_id_len)
1607
4.79k
            || !PACKET_get_sub_packet(pkt, &challenge, challenge_len)
1608
            /* No extensions. */
1609
4.72k
            || PACKET_remaining(pkt) != 0) {
1610
324
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_RECORD_LENGTH_MISMATCH);
1611
324
            goto err;
1612
324
        }
1613
4.55k
        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
4.55k
        challenge_len = challenge_len > SSL3_RANDOM_SIZE
1621
4.55k
            ? SSL3_RANDOM_SIZE
1622
4.55k
            : challenge_len;
1623
4.55k
        memset(clienthello->random, 0, SSL3_RANDOM_SIZE);
1624
4.55k
        if (!PACKET_copy_bytes(&challenge,
1625
4.55k
                clienthello->random + SSL3_RANDOM_SIZE - challenge_len, challenge_len)
1626
            /* Advertise only null compression. */
1627
4.55k
            || !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
4.55k
        PACKET_null_init(&clienthello->extensions);
1633
31.2k
    } else {
1634
        /* Regular ClientHello. */
1635
31.2k
        if (!PACKET_copy_bytes(pkt, clienthello->random, SSL3_RANDOM_SIZE)
1636
31.2k
            || !PACKET_get_length_prefixed_1(pkt, &session_id)
1637
31.1k
            || !PACKET_copy_all(&session_id, clienthello->session_id,
1638
31.1k
                SSL_MAX_SSL_SESSION_ID_LENGTH,
1639
31.1k
                &clienthello->session_id_len)) {
1640
118
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1641
118
            goto err;
1642
118
        }
1643
1644
31.1k
        if (SSL_CONNECTION_IS_DTLS(s)) {
1645
13.4k
            if (!PACKET_get_length_prefixed_1(pkt, &cookie)) {
1646
19
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1647
19
                goto err;
1648
19
            }
1649
13.4k
            if (!PACKET_copy_all(&cookie, clienthello->dtls_cookie,
1650
13.4k
                    DTLS1_COOKIE_LENGTH,
1651
13.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
13.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
13.4k
        }
1667
1668
31.1k
        if (!PACKET_get_length_prefixed_2(pkt, &clienthello->ciphersuites)) {
1669
120
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1670
120
            goto err;
1671
120
        }
1672
1673
31.0k
        if (!PACKET_get_length_prefixed_1(pkt, &compression)) {
1674
43
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1675
43
            goto err;
1676
43
        }
1677
1678
        /* Could be empty. */
1679
30.9k
        if (PACKET_remaining(pkt) == 0) {
1680
4.83k
            PACKET_null_init(&clienthello->extensions);
1681
26.1k
        } else {
1682
26.1k
            if (!PACKET_get_length_prefixed_2(pkt, &clienthello->extensions)
1683
26.0k
                || PACKET_remaining(pkt) != 0) {
1684
233
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1685
233
                goto err;
1686
233
            }
1687
26.1k
        }
1688
30.9k
    }
1689
1690
35.2k
    if (!PACKET_copy_all(&compression, clienthello->compressions,
1691
35.2k
            MAX_COMPRESSIONS_SIZE,
1692
35.2k
            &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
35.2k
    extensions = clienthello->extensions;
1699
35.2k
    if (!tls_collect_extensions(s, &extensions, SSL_EXT_CLIENT_HELLO,
1700
35.2k
            &clienthello->pre_proc_exts,
1701
35.2k
            &clienthello->pre_proc_exts_len, 1)) {
1702
        /* SSLfatal already been called */
1703
242
        goto err;
1704
242
    }
1705
35.0k
    s->clienthello = clienthello;
1706
1707
35.0k
    return MSG_PROCESS_CONTINUE_PROCESSING;
1708
1709
1.28k
err:
1710
1.28k
    if (clienthello != NULL)
1711
1.28k
        OPENSSL_free(clienthello->pre_proc_exts);
1712
1.28k
    OPENSSL_free(clienthello);
1713
1714
1.28k
    return MSG_PROCESS_ERROR;
1715
35.2k
}
1716
1717
static int tls_early_post_process_client_hello(SSL_CONNECTION *s)
1718
22.6k
{
1719
22.6k
    unsigned int j;
1720
22.6k
    int i, al = SSL_AD_INTERNAL_ERROR;
1721
22.6k
    int protverr;
1722
22.6k
    unsigned long id;
1723
22.6k
#ifndef OPENSSL_NO_COMP
1724
22.6k
    SSL_COMP *comp = NULL;
1725
22.6k
#endif
1726
22.6k
    const SSL_CIPHER *c;
1727
22.6k
    STACK_OF(SSL_CIPHER) *ciphers = NULL;
1728
22.6k
    STACK_OF(SSL_CIPHER) *scsvs = NULL;
1729
22.6k
    CLIENTHELLO_MSG *clienthello = s->clienthello;
1730
22.6k
    DOWNGRADE dgrd = DOWNGRADE_NONE;
1731
22.6k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1732
22.6k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1733
22.6k
    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
22.6k
    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
22.6k
    memcpy(s->s3.client_random, clienthello->random, SSL3_RANDOM_SIZE);
1754
1755
    /* Choose the version */
1756
1757
22.6k
    if (clienthello->isv2) {
1758
2.74k
        if (clienthello->legacy_version == SSL2_VERSION
1759
2.74k
            || (clienthello->legacy_version & 0xff00)
1760
2.74k
                != (SSL3_VERSION_MAJOR << 8)) {
1761
            /*
1762
             * This is real SSLv2 or something completely unknown. We don't
1763
             * support it.
1764
             */
1765
41
            SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_R_UNKNOWN_PROTOCOL);
1766
41
            goto err;
1767
41
        }
1768
        /* SSLv3/TLS */
1769
2.70k
        s->client_version = clienthello->legacy_version;
1770
2.70k
    }
1771
1772
    /* Choose the server SSL/TLS/DTLS version. */
1773
22.6k
    protverr = ssl_choose_server_version(s, clienthello, &dgrd);
1774
1775
22.6k
    if (protverr) {
1776
319
        if (SSL_IS_FIRST_HANDSHAKE(s)) {
1777
            /* like ssl3_get_record, send alert using remote version number */
1778
319
            s->version = s->client_version = clienthello->legacy_version;
1779
319
        }
1780
319
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION, protverr);
1781
319
        goto err;
1782
319
    }
1783
1784
    /* TLSv1.3 specifies that a ClientHello must end on a record boundary */
1785
22.2k
    if (SSL_CONNECTION_IS_TLS13(s)
1786
2.73k
        && RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1787
3
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
1788
3
        goto err;
1789
3
    }
1790
1791
22.2k
    if (SSL_CONNECTION_IS_DTLS(s)) {
1792
        /* Empty cookie was already handled above by returning early. */
1793
9.49k
        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
9.49k
    }
1814
1815
22.2k
    s->hit = 0;
1816
1817
22.2k
    if (!ssl_cache_cipherlist(s, &clienthello->ciphersuites,
1818
22.2k
            clienthello->isv2)
1819
22.2k
        || !ossl_bytes_to_cipher_list(s, &clienthello->ciphersuites, &ciphers,
1820
22.2k
            &scsvs, clienthello->isv2, 1)) {
1821
        /* SSLfatal() already called */
1822
52
        goto err;
1823
52
    }
1824
1825
22.2k
    s->s3.send_connection_binding = 0;
1826
    /* Check what signalling cipher-suite values were received. */
1827
22.2k
    if (scsvs != NULL) {
1828
30.3k
        for (i = 0; i < sk_SSL_CIPHER_num(scsvs); i++) {
1829
8.17k
            c = sk_SSL_CIPHER_value(scsvs, i);
1830
8.17k
            if (SSL_CIPHER_get_id(c) == SSL3_CK_SCSV) {
1831
7.82k
                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
7.82k
                s->s3.send_connection_binding = 1;
1838
7.82k
            } 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
20
                SSLfatal(s, SSL_AD_INAPPROPRIATE_FALLBACK,
1847
20
                    SSL_R_INAPPROPRIATE_FALLBACK);
1848
20
                goto err;
1849
20
            }
1850
8.17k
        }
1851
22.2k
    }
1852
1853
    /* For TLSv1.3 we must select the ciphersuite *before* session resumption */
1854
22.2k
    if (SSL_CONNECTION_IS_TLS13(s)) {
1855
2.73k
        const SSL_CIPHER *cipher = ssl3_choose_cipher(s, ciphers, SSL_get_ciphers(ssl));
1856
1857
2.73k
        if (cipher == NULL) {
1858
28
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
1859
28
            goto err;
1860
28
        }
1861
2.70k
        if (s->hello_retry_request == SSL_HRR_PENDING
1862
121
            && (s->s3.tmp.new_cipher == NULL
1863
121
                || 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
3
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_CIPHER);
1869
3
            goto err;
1870
3
        }
1871
2.70k
        s->s3.tmp.new_cipher = cipher;
1872
2.70k
    }
1873
1874
    /* We need to do this before getting the session */
1875
22.1k
    if (!tls_parse_extension(s, TLSEXT_IDX_extended_master_secret,
1876
22.1k
            SSL_EXT_CLIENT_HELLO,
1877
22.1k
            clienthello->pre_proc_exts, NULL, 0)) {
1878
        /* SSLfatal() already called */
1879
13
        goto err;
1880
13
    }
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
22.1k
    if (clienthello->isv2 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1899
2.66k
        if (!ssl_get_new_session(s, 1)) {
1900
            /* SSLfatal() already called */
1901
0
            goto err;
1902
0
        }
1903
19.5k
    } else {
1904
19.5k
        i = ssl_get_prev_session(s, clienthello);
1905
19.5k
        if (i == 1) {
1906
            /* previous session */
1907
151
            s->hit = 1;
1908
19.3k
        } else if (i == -1) {
1909
            /* SSLfatal() already called */
1910
290
            goto err;
1911
19.0k
        } else {
1912
            /* i == 0 */
1913
19.0k
            if (!ssl_get_new_session(s, 1)) {
1914
                /* SSLfatal() already called */
1915
0
                goto err;
1916
0
            }
1917
19.0k
        }
1918
19.5k
    }
1919
1920
21.8k
    if (SSL_CONNECTION_IS_TLS13(s)) {
1921
2.41k
        memcpy(s->tmp_session_id, s->clienthello->session_id,
1922
2.41k
            s->clienthello->session_id_len);
1923
2.41k
        s->tmp_session_id_len = s->clienthello->session_id_len;
1924
2.41k
    }
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
21.8k
    if (!SSL_CONNECTION_IS_TLS13(s) && s->hit) {
1931
151
        j = 0;
1932
151
        id = s->session->cipher->id;
1933
1934
151
        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
1.02k
        for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1940
989
            c = sk_SSL_CIPHER_value(ciphers, i);
1941
989
            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
989
            if (c->id == id) {
1945
116
                j = 1;
1946
116
                break;
1947
116
            }
1948
989
        }
1949
151
        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
35
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1955
35
                SSL_R_REQUIRED_CIPHER_MISSING);
1956
35
            OSSL_TRACE_CANCEL(TLS_CIPHER);
1957
35
            goto err;
1958
35
        }
1959
151
        OSSL_TRACE_END(TLS_CIPHER);
1960
151
    }
1961
1962
    /* At least one compression method must be preset. */
1963
21.8k
    if (clienthello->compressions_len == 0) {
1964
113
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_NO_COMPRESSION_SPECIFIED);
1965
113
        goto err;
1966
113
    }
1967
    /* Make sure at least the null compression is supported. */
1968
21.7k
    if (memchr(clienthello->compressions, 0,
1969
21.7k
            clienthello->compressions_len)
1970
21.7k
        == NULL) {
1971
76
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1972
76
            SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
1973
76
        goto err;
1974
76
    }
1975
1976
21.6k
    if (s->options & SSL_OP_SAFARI_ECDHE_ECDSA_BUG)
1977
0
        ssl_check_for_safari(s, clienthello);
1978
1979
    /* TLS extensions */
1980
21.6k
    if (!tls_parse_all_extensions(s, SSL_EXT_CLIENT_HELLO,
1981
21.6k
            clienthello->pre_proc_exts, NULL, 0, 1)) {
1982
        /* SSLfatal() already called */
1983
4.01k
        goto err;
1984
4.01k
    }
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
17.6k
    {
1993
17.6k
        unsigned char *pos;
1994
17.6k
        pos = s->s3.server_random;
1995
17.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
17.6k
    }
2000
2001
17.6k
    if (!s->hit && !tls1_set_server_sigalgs(s)) {
2002
        /* SSLfatal() already called */
2003
67
        goto err;
2004
67
    }
2005
2006
17.5k
    if (!s->hit
2007
17.4k
        && s->version >= TLS1_VERSION
2008
17.4k
        && !SSL_CONNECTION_IS_TLS13(s)
2009
15.6k
        && !SSL_CONNECTION_IS_DTLS(s)
2010
7.65k
        && 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
            /*
2030
             * Per RFC 4851, Section 3.2.2:
2031
             * If the ClientHello contains both a Session ID and a PAC-Opaque in
2032
             * the SessionTicket extension, and the server resumes the session
2033
             * using the PAC-Opaque, it should echo the same Session ID in the
2034
             * ServerHello.
2035
             */
2036
0
            if (clienthello->session_id_len > 0) {
2037
0
                memcpy(s->session->session_id, clienthello->session_id,
2038
0
                    clienthello->session_id_len);
2039
0
                s->session->session_id_length = clienthello->session_id_len;
2040
0
            }
2041
2042
0
            ciphers = NULL;
2043
2044
            /* check if some cipher was preferred by call back */
2045
0
            if (pref_cipher == NULL)
2046
0
                pref_cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2047
0
                    SSL_get_ciphers(ssl));
2048
0
            if (pref_cipher == NULL) {
2049
0
                SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_SHARED_CIPHER);
2050
0
                goto err;
2051
0
            }
2052
2053
0
            s->session->cipher = pref_cipher;
2054
0
            sk_SSL_CIPHER_free(s->cipher_list);
2055
0
            s->cipher_list = sk_SSL_CIPHER_dup(s->peer_ciphers);
2056
0
            sk_SSL_CIPHER_free(s->cipher_list_by_id);
2057
0
            s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->peer_ciphers);
2058
0
        }
2059
0
    }
2060
2061
    /*
2062
     * Worst case, we will use the NULL compression, but if we have other
2063
     * options, we will now look for them.  We have complen-1 compression
2064
     * algorithms from the client, starting at q.
2065
     */
2066
17.5k
    s->s3.tmp.new_compression = NULL;
2067
17.5k
    if (SSL_CONNECTION_IS_TLS13(s)) {
2068
        /*
2069
         * We already checked above that the NULL compression method appears in
2070
         * the list. Now we check there aren't any others (which is illegal in
2071
         * a TLSv1.3 ClientHello.
2072
         */
2073
1.84k
        if (clienthello->compressions_len != 1) {
2074
6
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2075
6
                SSL_R_INVALID_COMPRESSION_ALGORITHM);
2076
6
            goto err;
2077
6
        }
2078
1.84k
    }
2079
15.7k
#ifndef OPENSSL_NO_COMP
2080
    /* This only happens if we have a cache hit */
2081
15.7k
    else if (s->session->compress_meth != 0) {
2082
0
        int m, comp_id = s->session->compress_meth;
2083
0
        unsigned int k;
2084
        /* Perform sanity checks on resumed compression algorithm */
2085
        /* Can't disable compression */
2086
0
        if (!ssl_allow_compression(s)) {
2087
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2088
0
                SSL_R_INCONSISTENT_COMPRESSION);
2089
0
            goto err;
2090
0
        }
2091
        /* Look for resumed compression method */
2092
0
        for (m = 0; m < sk_SSL_COMP_num(sctx->comp_methods); m++) {
2093
0
            comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2094
0
            if (comp_id == comp->id) {
2095
0
                s->s3.tmp.new_compression = comp;
2096
0
                break;
2097
0
            }
2098
0
        }
2099
0
        if (s->s3.tmp.new_compression == NULL) {
2100
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2101
0
                SSL_R_INVALID_COMPRESSION_ALGORITHM);
2102
0
            goto err;
2103
0
        }
2104
        /* Look for resumed method in compression list */
2105
0
        for (k = 0; k < clienthello->compressions_len; k++) {
2106
0
            if (clienthello->compressions[k] == comp_id)
2107
0
                break;
2108
0
        }
2109
0
        if (k >= clienthello->compressions_len) {
2110
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
2111
0
                SSL_R_REQUIRED_COMPRESSION_ALGORITHM_MISSING);
2112
0
            goto err;
2113
0
        }
2114
15.7k
    } else if (s->hit) {
2115
99
        comp = NULL;
2116
15.6k
    } else if (ssl_allow_compression(s) && sctx->comp_methods) {
2117
        /* See if we have a match */
2118
0
        int m, nn, v, done = 0;
2119
0
        unsigned int o;
2120
2121
0
        nn = sk_SSL_COMP_num(sctx->comp_methods);
2122
0
        for (m = 0; m < nn; m++) {
2123
0
            comp = sk_SSL_COMP_value(sctx->comp_methods, m);
2124
0
            v = comp->id;
2125
0
            for (o = 0; o < clienthello->compressions_len; o++) {
2126
0
                if (v == clienthello->compressions[o]) {
2127
0
                    done = 1;
2128
0
                    break;
2129
0
                }
2130
0
            }
2131
0
            if (done)
2132
0
                break;
2133
0
        }
2134
0
        if (done)
2135
0
            s->s3.tmp.new_compression = comp;
2136
0
        else
2137
0
            comp = NULL;
2138
0
    }
2139
#else
2140
    /*
2141
     * If compression is disabled we'd better not try to resume a session
2142
     * using compression.
2143
     */
2144
    if (s->session->compress_meth != 0) {
2145
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
2146
        goto err;
2147
    }
2148
#endif
2149
2150
    /*
2151
     * Given s->peer_ciphers and SSL_get_ciphers, we must pick a cipher
2152
     */
2153
2154
17.5k
    if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2155
17.4k
        sk_SSL_CIPHER_free(s->peer_ciphers);
2156
17.4k
        s->peer_ciphers = ciphers;
2157
17.4k
        if (ciphers == NULL) {
2158
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2159
0
            goto err;
2160
0
        }
2161
17.4k
        ciphers = NULL;
2162
17.4k
    }
2163
2164
17.5k
    if (!s->hit) {
2165
#ifdef OPENSSL_NO_COMP
2166
        s->session->compress_meth = 0;
2167
#else
2168
17.4k
        s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
2169
17.4k
#endif
2170
17.4k
    }
2171
2172
17.5k
    sk_SSL_CIPHER_free(ciphers);
2173
17.5k
    sk_SSL_CIPHER_free(scsvs);
2174
17.5k
    OPENSSL_free(clienthello->pre_proc_exts);
2175
17.5k
    OPENSSL_free(s->clienthello);
2176
17.5k
    s->clienthello = NULL;
2177
17.5k
    return 1;
2178
5.07k
err:
2179
5.07k
    sk_SSL_CIPHER_free(ciphers);
2180
5.07k
    sk_SSL_CIPHER_free(scsvs);
2181
5.07k
    OPENSSL_free(clienthello->pre_proc_exts);
2182
5.07k
    OPENSSL_free(s->clienthello);
2183
5.07k
    s->clienthello = NULL;
2184
2185
5.07k
    return 0;
2186
17.5k
}
2187
2188
/*
2189
 * Call the status request callback if needed. Upon success, returns 1.
2190
 * Upon failure, returns 0.
2191
 */
2192
static int tls_handle_status_request(SSL_CONNECTION *s)
2193
19.2k
{
2194
19.2k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2195
2196
19.2k
    s->ext.status_expected = 0;
2197
2198
    /*
2199
     * If status request then ask callback what to do. Note: this must be
2200
     * called after servername callbacks in case the certificate has changed,
2201
     * and must be called after the cipher has been chosen because this may
2202
     * influence which certificate is sent
2203
     */
2204
19.2k
    if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing && sctx != NULL
2205
1.07k
        && sctx->ext.status_cb != NULL) {
2206
0
        int ret;
2207
2208
        /* If no certificate can't return certificate status */
2209
0
        if (s->s3.tmp.cert != NULL) {
2210
            /*
2211
             * Set current certificate to one we will use so SSL_get_certificate
2212
             * et al can pick it up.
2213
             */
2214
0
            s->cert->key = s->s3.tmp.cert;
2215
0
            ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),
2216
0
                sctx->ext.status_arg);
2217
0
            switch (ret) {
2218
                /* We don't want to send a status request response */
2219
0
            case SSL_TLSEXT_ERR_NOACK:
2220
0
                s->ext.status_expected = 0;
2221
0
                break;
2222
                /* status request response should be sent */
2223
0
            case SSL_TLSEXT_ERR_OK:
2224
0
                if (s->ext.ocsp.resp)
2225
0
                    s->ext.status_expected = 1;
2226
0
                break;
2227
                /* something bad happened */
2228
0
            case SSL_TLSEXT_ERR_ALERT_FATAL:
2229
0
            default:
2230
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CLIENTHELLO_TLSEXT);
2231
0
                return 0;
2232
0
            }
2233
0
        }
2234
0
    }
2235
2236
19.2k
    return 1;
2237
19.2k
}
2238
2239
/*
2240
 * Call the alpn_select callback if needed. Upon success, returns 1.
2241
 * Upon failure, returns 0.
2242
 */
2243
int tls_handle_alpn(SSL_CONNECTION *s)
2244
30.9k
{
2245
30.9k
    const unsigned char *selected = NULL;
2246
30.9k
    unsigned char selected_len = 0;
2247
30.9k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2248
2249
30.9k
    if (sctx->ext.alpn_select_cb != NULL && s->s3.alpn_proposed != NULL) {
2250
0
        int r = sctx->ext.alpn_select_cb(SSL_CONNECTION_GET_USER_SSL(s),
2251
0
            &selected, &selected_len,
2252
0
            s->s3.alpn_proposed,
2253
0
            (unsigned int)s->s3.alpn_proposed_len,
2254
0
            sctx->ext.alpn_select_cb_arg);
2255
2256
0
        if (r == SSL_TLSEXT_ERR_OK) {
2257
0
            OPENSSL_free(s->s3.alpn_selected);
2258
0
            s->s3.alpn_selected = OPENSSL_memdup(selected, selected_len);
2259
0
            if (s->s3.alpn_selected == NULL) {
2260
0
                s->s3.alpn_selected_len = 0;
2261
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2262
0
                return 0;
2263
0
            }
2264
0
            s->s3.alpn_selected_len = selected_len;
2265
0
#ifndef OPENSSL_NO_NEXTPROTONEG
2266
            /* ALPN takes precedence over NPN. */
2267
0
            s->s3.npn_seen = 0;
2268
0
#endif
2269
2270
            /* Check ALPN is consistent with session */
2271
0
            if (s->session->ext.alpn_selected == NULL
2272
0
                || selected_len != s->session->ext.alpn_selected_len
2273
0
                || memcmp(selected, s->session->ext.alpn_selected,
2274
0
                       selected_len)
2275
0
                    != 0) {
2276
                /* Not consistent so can't be used for early_data */
2277
0
                s->ext.early_data_ok = 0;
2278
2279
0
                if (!s->hit) {
2280
                    /*
2281
                     * This is a new session and so alpn_selected should have
2282
                     * been initialised to NULL. We should update it with the
2283
                     * selected ALPN.
2284
                     */
2285
0
                    if (!ossl_assert(s->session->ext.alpn_selected == NULL)) {
2286
0
                        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2287
0
                            ERR_R_INTERNAL_ERROR);
2288
0
                        return 0;
2289
0
                    }
2290
0
                    s->session->ext.alpn_selected = OPENSSL_memdup(selected,
2291
0
                        selected_len);
2292
0
                    if (s->session->ext.alpn_selected == NULL) {
2293
0
                        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2294
0
                            ERR_R_INTERNAL_ERROR);
2295
0
                        return 0;
2296
0
                    }
2297
0
                    s->session->ext.alpn_selected_len = selected_len;
2298
0
                }
2299
0
            }
2300
2301
0
            return 1;
2302
0
        } else if (r != SSL_TLSEXT_ERR_NOACK) {
2303
0
            SSLfatal(s, SSL_AD_NO_APPLICATION_PROTOCOL,
2304
0
                SSL_R_NO_APPLICATION_PROTOCOL);
2305
0
            return 0;
2306
0
        }
2307
        /*
2308
         * If r == SSL_TLSEXT_ERR_NOACK then behave as if no callback was
2309
         * present.
2310
         */
2311
0
    }
2312
2313
    /* Check ALPN is consistent with session */
2314
30.9k
    if (s->session->ext.alpn_selected != NULL) {
2315
        /* Not consistent so can't be used for early_data */
2316
0
        s->ext.early_data_ok = 0;
2317
0
    }
2318
2319
30.9k
    return 1;
2320
30.9k
}
2321
2322
WORK_STATE tls_post_process_client_hello(SSL_CONNECTION *s, WORK_STATE wst)
2323
42.5k
{
2324
42.5k
    const SSL_CIPHER *cipher;
2325
42.5k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
2326
42.5k
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
2327
2328
42.5k
    if (wst == WORK_MORE_A) {
2329
42.5k
        int rv = tls_early_post_process_client_hello(s);
2330
42.5k
        if (rv == 0) {
2331
            /* SSLfatal() was already called */
2332
9.12k
            goto err;
2333
9.12k
        }
2334
33.4k
        if (rv < 0)
2335
0
            return WORK_MORE_A;
2336
33.4k
        wst = WORK_MORE_B;
2337
33.4k
    }
2338
33.4k
    if (wst == WORK_MORE_B) {
2339
33.4k
        if (!s->hit || SSL_CONNECTION_IS_TLS13(s)) {
2340
            /* Let cert callback update server certificates if required */
2341
33.2k
            if (!s->hit && s->cert->cert_cb != NULL) {
2342
0
                int rv = s->cert->cert_cb(ussl, s->cert->cert_cb_arg);
2343
2344
0
                if (rv == 0) {
2345
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CERT_CB_ERROR);
2346
0
                    goto err;
2347
0
                }
2348
0
                if (rv < 0) {
2349
0
                    s->rwstate = SSL_X509_LOOKUP;
2350
0
                    return WORK_MORE_B;
2351
0
                }
2352
0
                s->rwstate = SSL_NOTHING;
2353
0
            }
2354
2355
            /* In TLSv1.3 we selected the ciphersuite before resumption */
2356
33.2k
            if (!SSL_CONNECTION_IS_TLS13(s)) {
2357
29.3k
                cipher = ssl3_choose_cipher(s, s->peer_ciphers,
2358
29.3k
                    SSL_get_ciphers(ssl));
2359
2360
29.3k
                if (cipher == NULL) {
2361
1.48k
                    SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2362
1.48k
                        SSL_R_NO_SHARED_CIPHER);
2363
1.48k
                    goto err;
2364
1.48k
                }
2365
27.8k
                s->s3.tmp.new_cipher = cipher;
2366
27.8k
            }
2367
31.7k
            if (!s->hit) {
2368
31.7k
                if (!tls_choose_sigalg(s, 1)) {
2369
                    /* SSLfatal already called */
2370
1.47k
                    goto err;
2371
1.47k
                }
2372
                /* check whether we should disable session resumption */
2373
30.2k
                if (s->not_resumable_session_cb != NULL)
2374
0
                    s->session->not_resumable = s->not_resumable_session_cb(ussl,
2375
0
                        ((s->s3.tmp.new_cipher->algorithm_mkey
2376
0
                             & (SSL_kDHE | SSL_kECDHE))
2377
0
                            != 0));
2378
30.2k
                if (s->session->not_resumable)
2379
                    /* do not send a session ticket */
2380
0
                    s->ext.ticket_expected = 0;
2381
30.2k
            }
2382
31.7k
        } else {
2383
            /* Session-id reuse */
2384
202
            s->s3.tmp.new_cipher = s->session->cipher;
2385
202
        }
2386
2387
        /*-
2388
         * we now have the following setup.
2389
         * client_random
2390
         * cipher_list          - our preferred list of ciphers
2391
         * ciphers              - the client's preferred list of ciphers
2392
         * compression          - basically ignored right now
2393
         * ssl version is set   - sslv3
2394
         * s->session           - The ssl session has been setup.
2395
         * s->hit               - session reuse flag
2396
         * s->s3.tmp.new_cipher - the new cipher to use.
2397
         */
2398
2399
        /*
2400
         * Call status_request callback if needed. Has to be done after the
2401
         * certificate callbacks etc above.
2402
         */
2403
30.4k
        if (!tls_handle_status_request(s)) {
2404
            /* SSLfatal() already called */
2405
0
            goto err;
2406
0
        }
2407
        /*
2408
         * Call alpn_select callback if needed.  Has to be done after SNI and
2409
         * cipher negotiation (HTTP/2 restricts permitted ciphers). In TLSv1.3
2410
         * we already did this because cipher negotiation happens earlier, and
2411
         * we must handle ALPN before we decide whether to accept early_data.
2412
         */
2413
30.4k
        if (!SSL_CONNECTION_IS_TLS13(s) && !tls_handle_alpn(s)) {
2414
            /* SSLfatal() already called */
2415
0
            goto err;
2416
0
        }
2417
2418
30.4k
        wst = WORK_MORE_C;
2419
30.4k
    }
2420
30.4k
#ifndef OPENSSL_NO_SRP
2421
30.4k
    if (wst == WORK_MORE_C) {
2422
30.4k
        int ret;
2423
30.4k
        if ((ret = ssl_check_srp_ext_ClientHello(s)) == 0) {
2424
            /*
2425
             * callback indicates further work to be done
2426
             */
2427
0
            s->rwstate = SSL_X509_LOOKUP;
2428
0
            return WORK_MORE_C;
2429
0
        }
2430
30.4k
        if (ret < 0) {
2431
            /* SSLfatal() already called */
2432
0
            goto err;
2433
0
        }
2434
30.4k
    }
2435
30.4k
#endif
2436
2437
30.4k
    return WORK_FINISHED_STOP;
2438
12.0k
err:
2439
12.0k
    return WORK_ERROR;
2440
30.4k
}
2441
2442
CON_FUNC_RETURN tls_construct_server_hello(SSL_CONNECTION *s, WPACKET *pkt)
2443
24.5k
{
2444
24.5k
    int compm;
2445
24.5k
    size_t sl, len;
2446
24.5k
    int version;
2447
24.5k
    unsigned char *session_id;
2448
24.5k
    int usetls13 = SSL_CONNECTION_IS_TLS13(s)
2449
21.6k
        || s->hello_retry_request == SSL_HRR_PENDING;
2450
2451
24.5k
    version = usetls13 ? TLS1_2_VERSION : s->version;
2452
24.5k
    if (!WPACKET_put_bytes_u16(pkt, version)
2453
        /*
2454
         * Random stuff. Filling of the server_random takes place in
2455
         * tls_process_client_hello()
2456
         */
2457
24.5k
        || !WPACKET_memcpy(pkt,
2458
24.5k
            s->hello_retry_request == SSL_HRR_PENDING
2459
24.5k
                ? hrrrandom
2460
24.5k
                : s->s3.server_random,
2461
24.5k
            SSL3_RANDOM_SIZE)) {
2462
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2463
0
        return CON_FUNC_ERROR;
2464
0
    }
2465
2466
    /*-
2467
     * There are several cases for the session ID to send
2468
     * back in the server hello:
2469
     * - For session reuse from the session cache,
2470
     *   we send back the old session ID.
2471
     * - If stateless session reuse (using a session ticket)
2472
     *   is successful, we send back the client's "session ID"
2473
     *   (which doesn't actually identify the session).
2474
     * - If it is a new session, we send back the new
2475
     *   session ID.
2476
     * - However, if we want the new session to be single-use,
2477
     *   we send back a 0-length session ID.
2478
     * - In TLSv1.3 we echo back the session id sent to us by the client
2479
     *   regardless
2480
     * s->hit is non-zero in either case of session reuse,
2481
     * so the following won't overwrite an ID that we're supposed
2482
     * to send back.
2483
     */
2484
24.5k
    if (!(SSL_CONNECTION_GET_CTX(s)->session_cache_mode & SSL_SESS_CACHE_SERVER)
2485
0
        && !s->hit)
2486
0
        s->session->session_id_length = 0;
2487
2488
24.5k
    if (usetls13) {
2489
2.97k
        sl = s->tmp_session_id_len;
2490
2.97k
        session_id = s->tmp_session_id;
2491
21.6k
    } else {
2492
21.6k
        sl = s->session->session_id_length;
2493
21.6k
        session_id = s->session->session_id;
2494
21.6k
    }
2495
2496
24.5k
    if (sl > sizeof(s->session->session_id)) {
2497
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2498
0
        return CON_FUNC_ERROR;
2499
0
    }
2500
2501
    /* set up the compression method */
2502
#ifdef OPENSSL_NO_COMP
2503
    compm = 0;
2504
#else
2505
24.5k
    if (usetls13 || s->s3.tmp.new_compression == NULL)
2506
24.5k
        compm = 0;
2507
0
    else
2508
0
        compm = s->s3.tmp.new_compression->id;
2509
24.5k
#endif
2510
2511
24.5k
    if (!WPACKET_sub_memcpy_u8(pkt, session_id, sl)
2512
24.5k
        || !SSL_CONNECTION_GET_SSL(s)->method->put_cipher_by_char(s->s3.tmp.new_cipher,
2513
24.5k
            pkt, &len)
2514
24.5k
        || !WPACKET_put_bytes_u8(pkt, compm)) {
2515
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2516
0
        return CON_FUNC_ERROR;
2517
0
    }
2518
2519
24.5k
    if (!tls_construct_extensions(s, pkt,
2520
24.5k
            s->hello_retry_request == SSL_HRR_PENDING
2521
24.5k
                ? SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST
2522
24.5k
                : (SSL_CONNECTION_IS_TLS13(s)
2523
23.9k
                          ? SSL_EXT_TLS1_3_SERVER_HELLO
2524
23.9k
                          : SSL_EXT_TLS1_2_SERVER_HELLO),
2525
24.5k
            NULL, 0)) {
2526
        /* SSLfatal() already called */
2527
13
        return CON_FUNC_ERROR;
2528
13
    }
2529
2530
24.5k
    if (s->hello_retry_request == SSL_HRR_PENDING) {
2531
        /* Ditch the session. We'll create a new one next time around */
2532
590
        SSL_SESSION_free(s->session);
2533
590
        s->session = NULL;
2534
590
        s->hit = 0;
2535
2536
        /*
2537
         * Re-initialise the Transcript Hash. We're going to prepopulate it with
2538
         * a synthetic message_hash in place of ClientHello1.
2539
         */
2540
590
        if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
2541
            /* SSLfatal() already called */
2542
0
            return CON_FUNC_ERROR;
2543
0
        }
2544
23.9k
    } else if (!(s->verify_mode & SSL_VERIFY_PEER)
2545
23.9k
        && !ssl3_digest_cached_records(s, 0)) {
2546
0
        /* SSLfatal() already called */;
2547
0
        return CON_FUNC_ERROR;
2548
0
    }
2549
2550
24.5k
    return CON_FUNC_SUCCESS;
2551
24.5k
}
2552
2553
CON_FUNC_RETURN tls_construct_server_done(SSL_CONNECTION *s, WPACKET *pkt)
2554
21.4k
{
2555
21.4k
    if (!s->s3.tmp.cert_request) {
2556
21.4k
        if (!ssl3_digest_cached_records(s, 0)) {
2557
            /* SSLfatal() already called */
2558
0
            return CON_FUNC_ERROR;
2559
0
        }
2560
21.4k
    }
2561
21.4k
    return CON_FUNC_SUCCESS;
2562
21.4k
}
2563
2564
CON_FUNC_RETURN tls_construct_server_key_exchange(SSL_CONNECTION *s,
2565
    WPACKET *pkt)
2566
9.35k
{
2567
9.35k
    EVP_PKEY *pkdh = NULL;
2568
9.35k
    unsigned char *encodedPoint = NULL;
2569
9.35k
    size_t encodedlen = 0;
2570
9.35k
    int curve_id = 0;
2571
9.35k
    const SIGALG_LOOKUP *lu = s->s3.tmp.sigalg;
2572
9.35k
    int i;
2573
9.35k
    unsigned long type;
2574
9.35k
    BIGNUM *r[4];
2575
9.35k
    EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
2576
9.35k
    EVP_PKEY_CTX *pctx = NULL;
2577
9.35k
    size_t paramlen, paramoffset;
2578
9.35k
    int freer = 0;
2579
9.35k
    CON_FUNC_RETURN ret = CON_FUNC_ERROR;
2580
9.35k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2581
2582
9.35k
    if (!WPACKET_get_total_written(pkt, &paramoffset)) {
2583
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2584
0
        goto err;
2585
0
    }
2586
2587
9.35k
    if (md_ctx == NULL) {
2588
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2589
0
        goto err;
2590
0
    }
2591
2592
9.35k
    type = s->s3.tmp.new_cipher->algorithm_mkey;
2593
2594
9.35k
    r[0] = r[1] = r[2] = r[3] = NULL;
2595
9.35k
#ifndef OPENSSL_NO_PSK
2596
    /* Plain PSK or RSAPSK nothing to do */
2597
9.35k
    if (type & (SSL_kPSK | SSL_kRSAPSK)) {
2598
0
    } else
2599
9.35k
#endif /* !OPENSSL_NO_PSK */
2600
9.35k
        if (type & (SSL_kDHE | SSL_kDHEPSK)) {
2601
0
            CERT *cert = s->cert;
2602
0
            EVP_PKEY *pkdhp = NULL;
2603
2604
0
            if (s->cert->dh_tmp_auto) {
2605
0
                pkdh = ssl_get_auto_dh(s);
2606
0
                if (pkdh == NULL) {
2607
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2608
0
                    goto err;
2609
0
                }
2610
0
                pkdhp = pkdh;
2611
0
            } else {
2612
0
                pkdhp = cert->dh_tmp;
2613
0
            }
2614
0
#if !defined(OPENSSL_NO_DEPRECATED_3_0)
2615
0
            if ((pkdhp == NULL) && (s->cert->dh_tmp_cb != NULL)) {
2616
0
                pkdh = ssl_dh_to_pkey(s->cert->dh_tmp_cb(SSL_CONNECTION_GET_USER_SSL(s),
2617
0
                    0, 1024));
2618
0
                if (pkdh == NULL) {
2619
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2620
0
                    goto err;
2621
0
                }
2622
0
                pkdhp = pkdh;
2623
0
            }
2624
0
#endif
2625
0
            if (pkdhp == NULL) {
2626
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
2627
0
                goto err;
2628
0
            }
2629
0
            if (!ssl_security(s, SSL_SECOP_TMP_DH,
2630
0
                    EVP_PKEY_get_security_bits(pkdhp), 0, pkdhp)) {
2631
0
                SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
2632
0
                goto err;
2633
0
            }
2634
0
            if (s->s3.tmp.pkey != NULL) {
2635
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2636
0
                goto err;
2637
0
            }
2638
2639
0
            s->s3.tmp.pkey = ssl_generate_pkey(s, pkdhp);
2640
0
            if (s->s3.tmp.pkey == NULL) {
2641
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2642
0
                goto err;
2643
0
            }
2644
2645
0
            EVP_PKEY_free(pkdh);
2646
0
            pkdh = NULL;
2647
2648
            /* These BIGNUMs need to be freed when we're finished */
2649
0
            freer = 1;
2650
0
            if (!EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_P,
2651
0
                    &r[0])
2652
0
                || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey, OSSL_PKEY_PARAM_FFC_G,
2653
0
                    &r[1])
2654
0
                || !EVP_PKEY_get_bn_param(s->s3.tmp.pkey,
2655
0
                    OSSL_PKEY_PARAM_PUB_KEY, &r[2])) {
2656
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2657
0
                goto err;
2658
0
            }
2659
9.35k
        } else if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2660
2661
9.35k
            if (s->s3.tmp.pkey != NULL) {
2662
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2663
0
                goto err;
2664
0
            }
2665
2666
            /* Get NID of appropriate shared curve */
2667
9.35k
            curve_id = tls1_shared_group(s, -2);
2668
9.35k
            if (curve_id == 0) {
2669
0
                SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
2670
0
                    SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
2671
0
                goto err;
2672
0
            }
2673
            /* Cache the group used in the SSL_SESSION */
2674
9.35k
            s->session->kex_group = curve_id;
2675
            /* Generate a new key for this curve */
2676
9.35k
            s->s3.tmp.pkey = ssl_generate_pkey_group(s, curve_id);
2677
9.35k
            if (s->s3.tmp.pkey == NULL) {
2678
                /* SSLfatal() already called */
2679
0
                goto err;
2680
0
            }
2681
2682
            /* Encode the public key. */
2683
9.35k
            encodedlen = EVP_PKEY_get1_encoded_public_key(s->s3.tmp.pkey,
2684
9.35k
                &encodedPoint);
2685
9.35k
            if (encodedlen == 0) {
2686
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
2687
0
                goto err;
2688
0
            }
2689
2690
            /*
2691
             * We'll generate the serverKeyExchange message explicitly so we
2692
             * can set these to NULLs
2693
             */
2694
9.35k
            r[0] = NULL;
2695
9.35k
            r[1] = NULL;
2696
9.35k
            r[2] = NULL;
2697
9.35k
            r[3] = NULL;
2698
9.35k
        } else
2699
0
#ifndef OPENSSL_NO_SRP
2700
0
            if (type & SSL_kSRP) {
2701
0
            if ((s->srp_ctx.N == NULL) || (s->srp_ctx.g == NULL) || (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
2702
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_SRP_PARAM);
2703
0
                goto err;
2704
0
            }
2705
0
            r[0] = s->srp_ctx.N;
2706
0
            r[1] = s->srp_ctx.g;
2707
0
            r[2] = s->srp_ctx.s;
2708
0
            r[3] = s->srp_ctx.B;
2709
0
        } else
2710
0
#endif
2711
0
        {
2712
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2713
0
            goto err;
2714
0
        }
2715
2716
9.35k
    if (((s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP)) != 0)
2717
7.39k
        || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)) != 0) {
2718
1.95k
        lu = NULL;
2719
7.39k
    } else if (lu == NULL) {
2720
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
2721
0
        goto err;
2722
0
    }
2723
2724
9.35k
#ifndef OPENSSL_NO_PSK
2725
9.35k
    if (type & SSL_PSK) {
2726
0
        size_t len = (s->cert->psk_identity_hint == NULL)
2727
0
            ? 0
2728
0
            : strlen(s->cert->psk_identity_hint);
2729
2730
        /*
2731
         * It should not happen that len > PSK_MAX_IDENTITY_LEN - we already
2732
         * checked this when we set the identity hint - but just in case
2733
         */
2734
0
        if (len > PSK_MAX_IDENTITY_LEN
2735
0
            || !WPACKET_sub_memcpy_u16(pkt, s->cert->psk_identity_hint,
2736
0
                len)) {
2737
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2738
0
            goto err;
2739
0
        }
2740
0
    }
2741
9.35k
#endif
2742
2743
9.35k
    for (i = 0; i < 4 && r[i] != NULL; i++) {
2744
0
        unsigned char *binval;
2745
0
        int res;
2746
2747
0
#ifndef OPENSSL_NO_SRP
2748
0
        if ((i == 2) && (type & SSL_kSRP)) {
2749
0
            res = WPACKET_start_sub_packet_u8(pkt);
2750
0
        } else
2751
0
#endif
2752
0
            res = WPACKET_start_sub_packet_u16(pkt);
2753
2754
0
        if (!res) {
2755
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2756
0
            goto err;
2757
0
        }
2758
2759
        /*-
2760
         * for interoperability with some versions of the Microsoft TLS
2761
         * stack, we need to zero pad the DHE pub key to the same length
2762
         * as the prime
2763
         */
2764
0
        if ((i == 2) && (type & (SSL_kDHE | SSL_kDHEPSK))) {
2765
0
            size_t len = BN_num_bytes(r[0]) - BN_num_bytes(r[2]);
2766
2767
0
            if (len > 0) {
2768
0
                if (!WPACKET_allocate_bytes(pkt, len, &binval)) {
2769
0
                    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2770
0
                    goto err;
2771
0
                }
2772
0
                memset(binval, 0, len);
2773
0
            }
2774
0
        }
2775
2776
0
        if (!WPACKET_allocate_bytes(pkt, BN_num_bytes(r[i]), &binval)
2777
0
            || !WPACKET_close(pkt)) {
2778
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2779
0
            goto err;
2780
0
        }
2781
2782
0
        BN_bn2bin(r[i], binval);
2783
0
    }
2784
2785
9.35k
    if (type & (SSL_kECDHE | SSL_kECDHEPSK)) {
2786
        /*
2787
         * We only support named (not generic) curves. In this situation, the
2788
         * ServerKeyExchange message has: [1 byte CurveType], [2 byte CurveName]
2789
         * [1 byte length of encoded point], followed by the actual encoded
2790
         * point itself
2791
         */
2792
9.35k
        if (!WPACKET_put_bytes_u8(pkt, NAMED_CURVE_TYPE)
2793
9.35k
            || !WPACKET_put_bytes_u8(pkt, 0)
2794
9.35k
            || !WPACKET_put_bytes_u8(pkt, curve_id)
2795
9.35k
            || !WPACKET_sub_memcpy_u8(pkt, encodedPoint, encodedlen)) {
2796
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2797
0
            goto err;
2798
0
        }
2799
9.35k
        OPENSSL_free(encodedPoint);
2800
9.35k
        encodedPoint = NULL;
2801
9.35k
    }
2802
2803
    /* not anonymous */
2804
9.35k
    if (lu != NULL) {
2805
7.39k
        EVP_PKEY *pkey = s->s3.tmp.cert->privatekey;
2806
7.39k
        const EVP_MD *md;
2807
7.39k
        unsigned char *sigbytes1, *sigbytes2, *tbs;
2808
7.39k
        size_t siglen = 0, tbslen;
2809
2810
7.39k
        if (pkey == NULL || !tls1_lookup_md(sctx, lu, &md)) {
2811
            /* Should never happen */
2812
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2813
0
            goto err;
2814
0
        }
2815
        /* Get length of the parameters we have written above */
2816
7.39k
        if (!WPACKET_get_length(pkt, &paramlen)) {
2817
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2818
0
            goto err;
2819
0
        }
2820
        /* send signature algorithm */
2821
7.39k
        if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2822
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2823
0
            goto err;
2824
0
        }
2825
2826
7.39k
        if (EVP_DigestSignInit_ex(md_ctx, &pctx,
2827
7.39k
                md == NULL ? NULL : EVP_MD_get0_name(md),
2828
7.39k
                sctx->libctx, sctx->propq, pkey,
2829
7.39k
                NULL)
2830
7.39k
            <= 0) {
2831
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2832
0
            goto err;
2833
0
        }
2834
7.39k
        if (lu->sig == EVP_PKEY_RSA_PSS) {
2835
642
            if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2836
642
                || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2837
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2838
0
                goto err;
2839
0
            }
2840
642
        }
2841
7.39k
        tbslen = construct_key_exchange_tbs(s, &tbs,
2842
7.39k
            s->init_buf->data + paramoffset,
2843
7.39k
            paramlen);
2844
7.39k
        if (tbslen == 0) {
2845
            /* SSLfatal() already called */
2846
0
            goto err;
2847
0
        }
2848
2849
7.39k
        if (EVP_DigestSign(md_ctx, NULL, &siglen, tbs, tbslen) <= 0
2850
7.39k
            || !WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2851
7.39k
            || EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen) <= 0
2852
7.39k
            || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2853
7.39k
            || sigbytes1 != sigbytes2) {
2854
0
            OPENSSL_free(tbs);
2855
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2856
0
            goto err;
2857
0
        }
2858
7.39k
        OPENSSL_free(tbs);
2859
7.39k
    }
2860
2861
9.35k
    ret = CON_FUNC_SUCCESS;
2862
9.35k
err:
2863
9.35k
    EVP_PKEY_free(pkdh);
2864
9.35k
    OPENSSL_free(encodedPoint);
2865
9.35k
    EVP_MD_CTX_free(md_ctx);
2866
9.35k
    if (freer) {
2867
0
        BN_free(r[0]);
2868
0
        BN_free(r[1]);
2869
0
        BN_free(r[2]);
2870
0
        BN_free(r[3]);
2871
0
    }
2872
9.35k
    return ret;
2873
9.35k
}
2874
2875
CON_FUNC_RETURN tls_construct_certificate_request(SSL_CONNECTION *s,
2876
    WPACKET *pkt)
2877
0
{
2878
0
    if (SSL_CONNECTION_IS_TLS13(s)) {
2879
        /* Send random context when doing post-handshake auth */
2880
0
        if (s->post_handshake_auth == SSL_PHA_REQUEST_PENDING) {
2881
0
            OPENSSL_free(s->pha_context);
2882
0
            s->pha_context_len = 32;
2883
0
            if ((s->pha_context = OPENSSL_malloc(s->pha_context_len)) == NULL) {
2884
0
                s->pha_context_len = 0;
2885
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2886
0
                return CON_FUNC_ERROR;
2887
0
            }
2888
0
            if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
2889
0
                    s->pha_context, s->pha_context_len, 0)
2890
0
                    <= 0
2891
0
                || !WPACKET_sub_memcpy_u8(pkt, s->pha_context,
2892
0
                    s->pha_context_len)) {
2893
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2894
0
                return CON_FUNC_ERROR;
2895
0
            }
2896
            /* reset the handshake hash back to just after the ClientFinished */
2897
0
            if (!tls13_restore_handshake_digest_for_pha(s)) {
2898
                /* SSLfatal() already called */
2899
0
                return CON_FUNC_ERROR;
2900
0
            }
2901
0
        } else {
2902
0
            if (!WPACKET_put_bytes_u8(pkt, 0)) {
2903
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2904
0
                return CON_FUNC_ERROR;
2905
0
            }
2906
0
        }
2907
2908
0
        if (!tls_construct_extensions(s, pkt,
2909
0
                SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2910
0
                0)) {
2911
            /* SSLfatal() already called */
2912
0
            return CON_FUNC_ERROR;
2913
0
        }
2914
0
        goto done;
2915
0
    }
2916
2917
    /* get the list of acceptable cert types */
2918
0
    if (!WPACKET_start_sub_packet_u8(pkt)
2919
0
        || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2920
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2921
0
        return CON_FUNC_ERROR;
2922
0
    }
2923
2924
0
    if (SSL_USE_SIGALGS(s)) {
2925
0
        const uint16_t *psigs;
2926
0
        size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2927
2928
0
        if (!WPACKET_start_sub_packet_u16(pkt)
2929
0
            || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2930
0
            || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2931
0
            || !WPACKET_close(pkt)) {
2932
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2933
0
            return CON_FUNC_ERROR;
2934
0
        }
2935
0
    }
2936
2937
0
    if (!construct_ca_names(s, get_ca_names(s), pkt)) {
2938
        /* SSLfatal() already called */
2939
0
        return CON_FUNC_ERROR;
2940
0
    }
2941
2942
0
done:
2943
0
    s->certreqs_sent++;
2944
0
    s->s3.tmp.cert_request = 1;
2945
0
    return CON_FUNC_SUCCESS;
2946
0
}
2947
2948
static int tls_process_cke_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)
2949
0
{
2950
0
#ifndef OPENSSL_NO_PSK
2951
0
    unsigned char psk[PSK_MAX_PSK_LEN];
2952
0
    size_t psklen;
2953
0
    PACKET psk_identity;
2954
2955
0
    if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2956
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2957
0
        return 0;
2958
0
    }
2959
0
    if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2960
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DATA_LENGTH_TOO_LONG);
2961
0
        return 0;
2962
0
    }
2963
0
    if (s->psk_server_callback == NULL) {
2964
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_SERVER_CB);
2965
0
        return 0;
2966
0
    }
2967
2968
0
    if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2969
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2970
0
        return 0;
2971
0
    }
2972
2973
0
    psklen = s->psk_server_callback(SSL_CONNECTION_GET_USER_SSL(s),
2974
0
        s->session->psk_identity,
2975
0
        psk, sizeof(psk));
2976
2977
0
    if (psklen > PSK_MAX_PSK_LEN) {
2978
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2979
0
        return 0;
2980
0
    } else if (psklen == 0) {
2981
        /*
2982
         * PSK related to the given identity not found
2983
         */
2984
0
        SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY, SSL_R_PSK_IDENTITY_NOT_FOUND);
2985
0
        return 0;
2986
0
    }
2987
2988
0
    OPENSSL_free(s->s3.tmp.psk);
2989
0
    s->s3.tmp.psk = OPENSSL_memdup(psk, psklen);
2990
0
    OPENSSL_cleanse(psk, psklen);
2991
2992
0
    if (s->s3.tmp.psk == NULL) {
2993
0
        s->s3.tmp.psklen = 0;
2994
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2995
0
        return 0;
2996
0
    }
2997
2998
0
    s->s3.tmp.psklen = psklen;
2999
3000
0
    return 1;
3001
#else
3002
    /* Should never happen */
3003
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3004
    return 0;
3005
#endif
3006
0
}
3007
3008
static int tls_process_cke_rsa(SSL_CONNECTION *s, PACKET *pkt)
3009
9.94k
{
3010
9.94k
    size_t outlen;
3011
9.94k
    PACKET enc_premaster;
3012
9.94k
    EVP_PKEY *rsa = NULL;
3013
9.94k
    unsigned char *rsa_decrypt = NULL;
3014
9.94k
    int ret = 0;
3015
9.94k
    EVP_PKEY_CTX *ctx = NULL;
3016
9.94k
    OSSL_PARAM params[3], *p = params;
3017
9.94k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3018
3019
9.94k
    rsa = s->cert->pkeys[SSL_PKEY_RSA].privatekey;
3020
9.94k
    if (rsa == NULL) {
3021
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_RSA_CERTIFICATE);
3022
0
        return 0;
3023
0
    }
3024
3025
    /* SSLv3 and pre-standard DTLS omit the length bytes. */
3026
9.94k
    if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
3027
0
        enc_premaster = *pkt;
3028
9.94k
    } else {
3029
9.94k
        if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
3030
9.83k
            || PACKET_remaining(pkt) != 0) {
3031
186
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3032
186
            return 0;
3033
186
        }
3034
9.94k
    }
3035
3036
9.76k
    outlen = SSL_MAX_MASTER_KEY_LENGTH;
3037
9.76k
    rsa_decrypt = OPENSSL_malloc(outlen);
3038
9.76k
    if (rsa_decrypt == NULL) {
3039
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3040
0
        return 0;
3041
0
    }
3042
3043
9.76k
    ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, rsa, sctx->propq);
3044
9.76k
    if (ctx == NULL) {
3045
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3046
0
        goto err;
3047
0
    }
3048
3049
    /*
3050
     * We must not leak whether a decryption failure occurs because of
3051
     * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
3052
     * section 7.4.7.1). We use the special padding type
3053
     * RSA_PKCS1_WITH_TLS_PADDING to do that. It will automatically decrypt the
3054
     * RSA, check the padding and check that the client version is as expected
3055
     * in the premaster secret. If any of that fails then the function appears
3056
     * to return successfully but with a random result. The call below could
3057
     * still fail if the input is publicly invalid.
3058
     * See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
3059
     */
3060
9.76k
    if (EVP_PKEY_decrypt_init(ctx) <= 0
3061
9.76k
        || EVP_PKEY_CTX_set_rsa_padding(ctx, RSA_PKCS1_WITH_TLS_PADDING) <= 0) {
3062
0
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3063
0
        goto err;
3064
0
    }
3065
3066
9.76k
    *p++ = OSSL_PARAM_construct_uint(OSSL_ASYM_CIPHER_PARAM_TLS_CLIENT_VERSION,
3067
9.76k
        (unsigned int *)&s->client_version);
3068
9.76k
    if ((s->options & SSL_OP_TLS_ROLLBACK_BUG) != 0)
3069
0
        *p++ = OSSL_PARAM_construct_uint(
3070
0
            OSSL_ASYM_CIPHER_PARAM_TLS_NEGOTIATED_VERSION,
3071
0
            (unsigned int *)&s->version);
3072
9.76k
    *p++ = OSSL_PARAM_construct_end();
3073
3074
9.76k
    if (!EVP_PKEY_CTX_set_params(ctx, params)
3075
9.76k
        || EVP_PKEY_decrypt(ctx, rsa_decrypt, &outlen,
3076
9.76k
               PACKET_data(&enc_premaster),
3077
9.76k
               PACKET_remaining(&enc_premaster))
3078
9.76k
            <= 0) {
3079
48
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3080
48
        goto err;
3081
48
    }
3082
3083
    /*
3084
     * This test should never fail (otherwise we should have failed above) but
3085
     * we double check anyway.
3086
     */
3087
9.71k
    if (outlen != SSL_MAX_MASTER_KEY_LENGTH) {
3088
0
        OPENSSL_cleanse(rsa_decrypt, SSL_MAX_MASTER_KEY_LENGTH);
3089
0
        SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_DECRYPTION_FAILED);
3090
0
        goto err;
3091
0
    }
3092
3093
    /* Also cleanses rsa_decrypt (on success or failure) */
3094
9.71k
    if (!ssl_generate_master_secret(s, rsa_decrypt, outlen, 0)) {
3095
        /* SSLfatal() already called */
3096
0
        goto err;
3097
0
    }
3098
3099
9.71k
    ret = 1;
3100
9.76k
err:
3101
9.76k
    OPENSSL_free(rsa_decrypt);
3102
9.76k
    EVP_PKEY_CTX_free(ctx);
3103
9.76k
    return ret;
3104
9.71k
}
3105
3106
static int tls_process_cke_dhe(SSL_CONNECTION *s, PACKET *pkt)
3107
13
{
3108
13
    EVP_PKEY *skey = NULL;
3109
13
    unsigned int i;
3110
13
    const unsigned char *data;
3111
13
    EVP_PKEY *ckey = NULL;
3112
13
    int ret = 0;
3113
3114
13
    if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
3115
6
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
3116
6
        goto err;
3117
6
    }
3118
7
    skey = s->s3.tmp.pkey;
3119
7
    if (skey == NULL) {
3120
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3121
0
        goto err;
3122
0
    }
3123
3124
7
    if (PACKET_remaining(pkt) == 0L) {
3125
1
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_MISSING_TMP_DH_KEY);
3126
1
        goto err;
3127
1
    }
3128
6
    if (!PACKET_get_bytes(pkt, &data, i)) {
3129
        /* We already checked we have enough data */
3130
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3131
0
        goto err;
3132
0
    }
3133
6
    ckey = EVP_PKEY_new();
3134
6
    if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3135
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3136
0
        goto err;
3137
0
    }
3138
3139
6
    if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3140
1
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3141
1
        goto err;
3142
1
    }
3143
3144
5
    if (ssl_derive(s, skey, ckey, 1) == 0) {
3145
        /* SSLfatal() already called */
3146
0
        goto err;
3147
0
    }
3148
3149
5
    ret = 1;
3150
5
    EVP_PKEY_free(s->s3.tmp.pkey);
3151
5
    s->s3.tmp.pkey = NULL;
3152
13
err:
3153
13
    EVP_PKEY_free(ckey);
3154
13
    return ret;
3155
5
}
3156
3157
static int tls_process_cke_ecdhe(SSL_CONNECTION *s, PACKET *pkt)
3158
4.77k
{
3159
4.77k
    EVP_PKEY *skey = s->s3.tmp.pkey;
3160
4.77k
    EVP_PKEY *ckey = NULL;
3161
4.77k
    int ret = 0;
3162
3163
4.77k
    if (PACKET_remaining(pkt) == 0L) {
3164
        /* We don't support ECDH client auth */
3165
33
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_TMP_ECDH_KEY);
3166
33
        goto err;
3167
4.73k
    } else {
3168
4.73k
        unsigned int i;
3169
4.73k
        const unsigned char *data;
3170
3171
        /*
3172
         * Get client's public key from encoded point in the
3173
         * ClientKeyExchange message.
3174
         */
3175
3176
        /* Get encoded point length */
3177
4.73k
        if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3178
4.67k
            || PACKET_remaining(pkt) != 0) {
3179
107
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3180
107
            goto err;
3181
107
        }
3182
4.63k
        if (skey == NULL) {
3183
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_MISSING_TMP_ECDH_KEY);
3184
0
            goto err;
3185
0
        }
3186
3187
4.63k
        ckey = EVP_PKEY_new();
3188
4.63k
        if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3189
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COPY_PARAMETERS_FAILED);
3190
0
            goto err;
3191
0
        }
3192
3193
4.63k
        if (EVP_PKEY_set1_encoded_public_key(ckey, data, i) <= 0) {
3194
761
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_KEY_SHARE);
3195
761
            goto err;
3196
761
        }
3197
4.63k
    }
3198
3199
3.87k
    if (ssl_derive(s, skey, ckey, 1) == 0) {
3200
        /* SSLfatal() already called */
3201
30
        goto err;
3202
30
    }
3203
3204
3.84k
    ret = 1;
3205
3.84k
    EVP_PKEY_free(s->s3.tmp.pkey);
3206
3.84k
    s->s3.tmp.pkey = NULL;
3207
4.77k
err:
3208
4.77k
    EVP_PKEY_free(ckey);
3209
3210
4.77k
    return ret;
3211
3.84k
}
3212
3213
static int tls_process_cke_srp(SSL_CONNECTION *s, PACKET *pkt)
3214
0
{
3215
0
#ifndef OPENSSL_NO_SRP
3216
0
    unsigned int i;
3217
0
    const unsigned char *data;
3218
3219
0
    if (!PACKET_get_net_2(pkt, &i)
3220
0
        || !PACKET_get_bytes(pkt, &data, i)) {
3221
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_SRP_A_LENGTH);
3222
0
        return 0;
3223
0
    }
3224
0
    if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3225
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
3226
0
        return 0;
3227
0
    }
3228
0
    if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3229
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_SRP_PARAMETERS);
3230
0
        return 0;
3231
0
    }
3232
0
    OPENSSL_free(s->session->srp_username);
3233
0
    s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3234
0
    if (s->session->srp_username == NULL) {
3235
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3236
0
        return 0;
3237
0
    }
3238
3239
0
    if (!srp_generate_server_master_secret(s)) {
3240
        /* SSLfatal() already called */
3241
0
        return 0;
3242
0
    }
3243
3244
0
    return 1;
3245
#else
3246
    /* Should never happen */
3247
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3248
    return 0;
3249
#endif
3250
0
}
3251
3252
static int tls_process_cke_gost(SSL_CONNECTION *s, PACKET *pkt)
3253
0
{
3254
0
#ifndef OPENSSL_NO_GOST
3255
0
    EVP_PKEY_CTX *pkey_ctx;
3256
0
    EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3257
0
    unsigned char premaster_secret[32];
3258
0
    const unsigned char *start;
3259
0
    size_t outlen = sizeof(premaster_secret), inlen;
3260
0
    unsigned long alg_a;
3261
0
    GOST_KX_MESSAGE *pKX = NULL;
3262
0
    const unsigned char *ptr;
3263
0
    int ret = 0;
3264
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3265
3266
    /* Get our certificate private key */
3267
0
    alg_a = s->s3.tmp.new_cipher->algorithm_auth;
3268
0
    if (alg_a & SSL_aGOST12) {
3269
        /*
3270
         * New GOST ciphersuites have SSL_aGOST01 bit too
3271
         */
3272
0
        pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3273
0
        if (pk == NULL) {
3274
0
            pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3275
0
        }
3276
0
        if (pk == NULL) {
3277
0
            pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3278
0
        }
3279
0
    } else if (alg_a & SSL_aGOST01) {
3280
0
        pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3281
0
    }
3282
3283
0
    pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3284
0
    if (pkey_ctx == NULL) {
3285
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3286
0
        return 0;
3287
0
    }
3288
0
    if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3289
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3290
0
        goto err;
3291
0
    }
3292
    /*
3293
     * If client certificate is present and is of the same type, maybe
3294
     * use it for key exchange.  Don't mind errors from
3295
     * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3296
     * client certificate for authorization only.
3297
     */
3298
0
    client_pub_pkey = tls_get_peer_pkey(s);
3299
0
    if (client_pub_pkey) {
3300
0
        if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3301
0
            ERR_clear_error();
3302
0
    }
3303
3304
0
    ptr = PACKET_data(pkt);
3305
    /* Some implementations provide extra data in the opaqueBlob
3306
     * We have nothing to do with this blob so we just skip it */
3307
0
    pKX = d2i_GOST_KX_MESSAGE(NULL, &ptr, PACKET_remaining(pkt));
3308
0
    if (pKX == NULL
3309
0
        || pKX->kxBlob == NULL
3310
0
        || ASN1_TYPE_get(pKX->kxBlob) != V_ASN1_SEQUENCE) {
3311
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3312
0
        goto err;
3313
0
    }
3314
3315
0
    if (!PACKET_forward(pkt, ptr - PACKET_data(pkt))) {
3316
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3317
0
        goto err;
3318
0
    }
3319
3320
0
    if (PACKET_remaining(pkt) != 0) {
3321
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_DECRYPTION_FAILED);
3322
0
        goto err;
3323
0
    }
3324
3325
0
    inlen = pKX->kxBlob->value.sequence->length;
3326
0
    start = pKX->kxBlob->value.sequence->data;
3327
3328
0
    if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3329
0
            inlen)
3330
0
        <= 0) {
3331
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3332
0
        goto err;
3333
0
    }
3334
    /* Generate master secret */
3335
0
    if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3336
        /* SSLfatal() already called */
3337
0
        goto err;
3338
0
    }
3339
    /* Check if pubkey from client certificate was used */
3340
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3341
0
            NULL)
3342
0
        > 0)
3343
0
        s->statem.no_cert_verify = 1;
3344
3345
0
    ret = 1;
3346
0
err:
3347
0
    EVP_PKEY_CTX_free(pkey_ctx);
3348
0
    GOST_KX_MESSAGE_free(pKX);
3349
0
    return ret;
3350
#else
3351
    /* Should never happen */
3352
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3353
    return 0;
3354
#endif
3355
0
}
3356
3357
static int tls_process_cke_gost18(SSL_CONNECTION *s, PACKET *pkt)
3358
0
{
3359
0
#ifndef OPENSSL_NO_GOST
3360
0
    unsigned char rnd_dgst[32];
3361
0
    EVP_PKEY_CTX *pkey_ctx = NULL;
3362
0
    EVP_PKEY *pk = NULL;
3363
0
    unsigned char premaster_secret[32];
3364
0
    const unsigned char *start = NULL;
3365
0
    size_t outlen = sizeof(premaster_secret), inlen = 0;
3366
0
    int ret = 0;
3367
0
    int cipher_nid = ossl_gost18_cke_cipher_nid(s);
3368
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3369
3370
0
    if (cipher_nid == NID_undef) {
3371
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3372
0
        return 0;
3373
0
    }
3374
3375
0
    if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
3376
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3377
0
        goto err;
3378
0
    }
3379
3380
    /* Get our certificate private key */
3381
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;
3382
0
    if (pk == NULL) {
3383
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
3384
0
        goto err;
3385
0
    }
3386
3387
0
    pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pk, sctx->propq);
3388
0
    if (pkey_ctx == NULL) {
3389
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3390
0
        goto err;
3391
0
    }
3392
0
    if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3393
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3394
0
        goto err;
3395
0
    }
3396
3397
    /* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code depending on size */
3398
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3399
0
            EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst)
3400
0
        <= 0) {
3401
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3402
0
        goto err;
3403
0
    }
3404
3405
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_DECRYPT,
3406
0
            EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL)
3407
0
        <= 0) {
3408
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3409
0
        goto err;
3410
0
    }
3411
0
    inlen = PACKET_remaining(pkt);
3412
0
    start = PACKET_data(pkt);
3413
3414
0
    if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
3415
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_DECRYPTION_FAILED);
3416
0
        goto err;
3417
0
    }
3418
    /* Generate master secret */
3419
0
    if (!ssl_generate_master_secret(s, premaster_secret, outlen, 0)) {
3420
        /* SSLfatal() already called */
3421
0
        goto err;
3422
0
    }
3423
0
    ret = 1;
3424
3425
0
err:
3426
0
    EVP_PKEY_CTX_free(pkey_ctx);
3427
0
    return ret;
3428
#else
3429
    /* Should never happen */
3430
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3431
    return 0;
3432
#endif
3433
0
}
3434
3435
MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL_CONNECTION *s,
3436
    PACKET *pkt)
3437
19.5k
{
3438
19.5k
    unsigned long alg_k;
3439
3440
19.5k
    alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3441
3442
    /* For PSK parse and retrieve identity, obtain PSK key */
3443
19.5k
    if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3444
        /* SSLfatal() already called */
3445
0
        goto err;
3446
0
    }
3447
3448
19.5k
    if (alg_k & SSL_kPSK) {
3449
        /* Identity extracted earlier: should be nothing left */
3450
0
        if (PACKET_remaining(pkt) != 0) {
3451
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3452
0
            goto err;
3453
0
        }
3454
        /* PSK handled by ssl_generate_master_secret */
3455
0
        if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3456
            /* SSLfatal() already called */
3457
0
            goto err;
3458
0
        }
3459
19.5k
    } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3460
11.3k
        if (!tls_process_cke_rsa(s, pkt)) {
3461
            /* SSLfatal() already called */
3462
266
            goto err;
3463
266
        }
3464
11.3k
    } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3465
13
        if (!tls_process_cke_dhe(s, pkt)) {
3466
            /* SSLfatal() already called */
3467
8
            goto err;
3468
8
        }
3469
8.15k
    } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3470
8.15k
        if (!tls_process_cke_ecdhe(s, pkt)) {
3471
            /* SSLfatal() already called */
3472
1.68k
            goto err;
3473
1.68k
        }
3474
8.15k
    } else if (alg_k & SSL_kSRP) {
3475
0
        if (!tls_process_cke_srp(s, pkt)) {
3476
            /* SSLfatal() already called */
3477
0
            goto err;
3478
0
        }
3479
0
    } else if (alg_k & SSL_kGOST) {
3480
0
        if (!tls_process_cke_gost(s, pkt)) {
3481
            /* SSLfatal() already called */
3482
0
            goto err;
3483
0
        }
3484
0
    } else if (alg_k & SSL_kGOST18) {
3485
0
        if (!tls_process_cke_gost18(s, pkt)) {
3486
            /* SSLfatal() already called */
3487
0
            goto err;
3488
0
        }
3489
0
    } else {
3490
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
3491
0
        goto err;
3492
0
    }
3493
3494
17.6k
    return MSG_PROCESS_CONTINUE_PROCESSING;
3495
1.96k
err:
3496
1.96k
#ifndef OPENSSL_NO_PSK
3497
1.96k
    OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3498
1.96k
    s->s3.tmp.psk = NULL;
3499
1.96k
    s->s3.tmp.psklen = 0;
3500
1.96k
#endif
3501
1.96k
    return MSG_PROCESS_ERROR;
3502
19.5k
}
3503
3504
WORK_STATE tls_post_process_client_key_exchange(SSL_CONNECTION *s,
3505
    WORK_STATE wst)
3506
17.6k
{
3507
#ifndef OPENSSL_NO_SCTP
3508
    if (wst == WORK_MORE_A) {
3509
        if (SSL_CONNECTION_IS_DTLS(s)) {
3510
            unsigned char sctpauthkey[64];
3511
            char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3512
            size_t labellen;
3513
            /*
3514
             * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3515
             * used.
3516
             */
3517
            memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3518
                sizeof(DTLS1_SCTP_AUTH_LABEL));
3519
3520
            /* Don't include the terminating zero. */
3521
            labellen = sizeof(labelbuffer) - 1;
3522
            if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3523
                labellen += 1;
3524
3525
            if (SSL_export_keying_material(SSL_CONNECTION_GET_SSL(s),
3526
                    sctpauthkey,
3527
                    sizeof(sctpauthkey), labelbuffer,
3528
                    labellen, NULL, 0,
3529
                    0)
3530
                <= 0) {
3531
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3532
                return WORK_ERROR;
3533
            }
3534
3535
            BIO_ctrl(s->wbio, BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3536
                sizeof(sctpauthkey), sctpauthkey);
3537
        }
3538
    }
3539
#endif
3540
3541
17.6k
    if (s->statem.no_cert_verify || !received_client_cert(s)) {
3542
        /*
3543
         * No certificate verify or no peer certificate so we no longer need
3544
         * the handshake_buffer
3545
         */
3546
17.6k
        if (!ssl3_digest_cached_records(s, 0)) {
3547
            /* SSLfatal() already called */
3548
0
            return WORK_ERROR;
3549
0
        }
3550
17.6k
        return WORK_FINISHED_CONTINUE;
3551
17.6k
    } else {
3552
0
        if (!s->s3.handshake_buffer) {
3553
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3554
0
            return WORK_ERROR;
3555
0
        }
3556
        /*
3557
         * For sigalgs freeze the handshake buffer. If we support
3558
         * extms we've done this already so this is a no-op
3559
         */
3560
0
        if (!ssl3_digest_cached_records(s, 1)) {
3561
            /* SSLfatal() already called */
3562
0
            return WORK_ERROR;
3563
0
        }
3564
0
    }
3565
3566
0
    return WORK_FINISHED_CONTINUE;
3567
17.6k
}
3568
3569
MSG_PROCESS_RETURN tls_process_client_rpk(SSL_CONNECTION *sc, PACKET *pkt)
3570
0
{
3571
0
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3572
0
    SSL_SESSION *new_sess = NULL;
3573
0
    EVP_PKEY *peer_rpk = NULL;
3574
3575
0
    if (!tls_process_rpk(sc, pkt, &peer_rpk)) {
3576
        /* SSLfatal already called */
3577
0
        goto err;
3578
0
    }
3579
3580
0
    if (peer_rpk == NULL) {
3581
0
        if ((sc->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)
3582
0
            && (sc->verify_mode & SSL_VERIFY_PEER)) {
3583
0
            SSLfatal(sc, SSL_AD_CERTIFICATE_REQUIRED,
3584
0
                SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3585
0
            goto err;
3586
0
        }
3587
0
    } else {
3588
0
        if (ssl_verify_rpk(sc, peer_rpk) <= 0) {
3589
0
            SSLfatal(sc, ssl_x509err2alert(sc->verify_result),
3590
0
                SSL_R_CERTIFICATE_VERIFY_FAILED);
3591
0
            goto err;
3592
0
        }
3593
0
    }
3594
3595
    /*
3596
     * Sessions must be immutable once they go into the session cache. Otherwise
3597
     * we can get multi-thread problems. Therefore we don't "update" sessions,
3598
     * we replace them with a duplicate. Here, we need to do this every time
3599
     * a new RPK (or certificate) is received via post-handshake authentication,
3600
     * as the session may have already gone into the session cache.
3601
     */
3602
3603
0
    if (sc->post_handshake_auth == SSL_PHA_REQUESTED) {
3604
0
        if ((new_sess = ssl_session_dup(sc->session, 0)) == NULL) {
3605
0
            SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
3606
0
            goto err;
3607
0
        }
3608
3609
0
        SSL_SESSION_free(sc->session);
3610
0
        sc->session = new_sess;
3611
0
    }
3612
3613
    /* Ensure there is no peer/peer_chain */
3614
0
    X509_free(sc->session->peer);
3615
0
    sc->session->peer = NULL;
3616
0
    sk_X509_pop_free(sc->session->peer_chain, X509_free);
3617
0
    sc->session->peer_chain = NULL;
3618
    /* Save RPK */
3619
0
    EVP_PKEY_free(sc->session->peer_rpk);
3620
0
    sc->session->peer_rpk = peer_rpk;
3621
0
    peer_rpk = NULL;
3622
3623
0
    sc->session->verify_result = sc->verify_result;
3624
3625
    /*
3626
     * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3627
     * message
3628
     */
3629
0
    if (SSL_CONNECTION_IS_TLS13(sc)) {
3630
0
        if (!ssl3_digest_cached_records(sc, 1)) {
3631
            /* SSLfatal() already called */
3632
0
            goto err;
3633
0
        }
3634
3635
        /* Save the current hash state for when we receive the CertificateVerify */
3636
0
        if (!ssl_handshake_hash(sc, sc->cert_verify_hash,
3637
0
                sizeof(sc->cert_verify_hash),
3638
0
                &sc->cert_verify_hash_len)) {
3639
0
            /* SSLfatal() already called */;
3640
0
            goto err;
3641
0
        }
3642
3643
        /* resend session tickets */
3644
0
        sc->sent_tickets = 0;
3645
0
    }
3646
3647
0
    ret = MSG_PROCESS_CONTINUE_READING;
3648
3649
0
err:
3650
0
    EVP_PKEY_free(peer_rpk);
3651
0
    return ret;
3652
0
}
3653
3654
MSG_PROCESS_RETURN tls_process_client_certificate(SSL_CONNECTION *s,
3655
    PACKET *pkt)
3656
0
{
3657
0
    int i;
3658
0
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3659
0
    X509 *x = NULL;
3660
0
    unsigned long l;
3661
0
    const unsigned char *certstart, *certbytes;
3662
0
    STACK_OF(X509) *sk = NULL;
3663
0
    PACKET spkt, context;
3664
0
    size_t chainidx;
3665
0
    SSL_SESSION *new_sess = NULL;
3666
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3667
3668
    /*
3669
     * To get this far we must have read encrypted data from the client. We no
3670
     * longer tolerate unencrypted alerts. This is ignored if less than TLSv1.3
3671
     */
3672
0
    if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
3673
0
        s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 0);
3674
3675
0
    if (s->ext.client_cert_type == TLSEXT_cert_type_rpk)
3676
0
        return tls_process_client_rpk(s, pkt);
3677
3678
0
    if (s->ext.client_cert_type != TLSEXT_cert_type_x509) {
3679
0
        SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,
3680
0
            SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3681
0
        goto err;
3682
0
    }
3683
3684
0
    if ((sk = sk_X509_new_null()) == NULL) {
3685
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3686
0
        goto err;
3687
0
    }
3688
3689
0
    if (SSL_CONNECTION_IS_TLS13(s)
3690
0
        && (!PACKET_get_length_prefixed_1(pkt, &context)
3691
0
            || (s->pha_context == NULL && PACKET_remaining(&context) != 0)
3692
0
            || (s->pha_context != NULL
3693
0
                && !PACKET_equal(&context, s->pha_context,
3694
0
                    s->pha_context_len)))) {
3695
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_INVALID_CONTEXT);
3696
0
        goto err;
3697
0
    }
3698
3699
0
    if (!PACKET_get_length_prefixed_3(pkt, &spkt)
3700
0
        || PACKET_remaining(pkt) != 0) {
3701
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3702
0
        goto err;
3703
0
    }
3704
3705
0
    for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3706
0
        if (!PACKET_get_net_3(&spkt, &l)
3707
0
            || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3708
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3709
0
            goto err;
3710
0
        }
3711
3712
0
        certstart = certbytes;
3713
0
        x = X509_new_ex(sctx->libctx, sctx->propq);
3714
0
        if (x == NULL) {
3715
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_X509_LIB);
3716
0
            goto err;
3717
0
        }
3718
0
        if (d2i_X509(&x, (const unsigned char **)&certbytes, l) == NULL) {
3719
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
3720
0
            goto err;
3721
0
        }
3722
3723
0
        if (certbytes != (certstart + l)) {
3724
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
3725
0
            goto err;
3726
0
        }
3727
3728
0
        if (SSL_CONNECTION_IS_TLS13(s)) {
3729
0
            RAW_EXTENSION *rawexts = NULL;
3730
0
            PACKET extensions;
3731
3732
0
            if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3733
0
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
3734
0
                goto err;
3735
0
            }
3736
0
            if (!tls_collect_extensions(s, &extensions,
3737
0
                    SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3738
0
                    NULL, chainidx == 0)
3739
0
                || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3740
0
                    rawexts, x, chainidx,
3741
0
                    PACKET_remaining(&spkt) == 0)) {
3742
0
                OPENSSL_free(rawexts);
3743
0
                goto err;
3744
0
            }
3745
0
            OPENSSL_free(rawexts);
3746
0
        }
3747
3748
0
        if (!sk_X509_push(sk, x)) {
3749
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3750
0
            goto err;
3751
0
        }
3752
0
        x = NULL;
3753
0
    }
3754
3755
0
    if (sk_X509_num(sk) <= 0) {
3756
        /* TLS does not mind 0 certs returned */
3757
0
        if (s->version == SSL3_VERSION) {
3758
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3759
0
                SSL_R_NO_CERTIFICATES_RETURNED);
3760
0
            goto err;
3761
0
        }
3762
        /* Fail for TLS only if we required a certificate */
3763
0
        else if ((s->verify_mode & SSL_VERIFY_PEER) && (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3764
0
            SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3765
0
                SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3766
0
            goto err;
3767
0
        }
3768
        /* No client certificate so digest cached records */
3769
0
        if (s->s3.handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3770
            /* SSLfatal() already called */
3771
0
            goto err;
3772
0
        }
3773
0
    } else {
3774
0
        EVP_PKEY *pkey;
3775
0
        i = ssl_verify_cert_chain(s, sk);
3776
0
        if (i <= 0) {
3777
0
            SSLfatal(s, ssl_x509err2alert(s->verify_result),
3778
0
                SSL_R_CERTIFICATE_VERIFY_FAILED);
3779
0
            goto err;
3780
0
        }
3781
0
        pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3782
0
        if (pkey == NULL) {
3783
0
            SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3784
0
                SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3785
0
            goto err;
3786
0
        }
3787
0
    }
3788
3789
    /*
3790
     * Sessions must be immutable once they go into the session cache. Otherwise
3791
     * we can get multi-thread problems. Therefore we don't "update" sessions,
3792
     * we replace them with a duplicate. Here, we need to do this every time
3793
     * a new certificate is received via post-handshake authentication, as the
3794
     * session may have already gone into the session cache.
3795
     */
3796
3797
0
    if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3798
0
        if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
3799
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
3800
0
            goto err;
3801
0
        }
3802
3803
0
        SSL_SESSION_free(s->session);
3804
0
        s->session = new_sess;
3805
0
    }
3806
3807
0
    X509_free(s->session->peer);
3808
0
    s->session->peer = sk_X509_shift(sk);
3809
0
    s->session->verify_result = s->verify_result;
3810
3811
0
    OSSL_STACK_OF_X509_free(s->session->peer_chain);
3812
0
    s->session->peer_chain = sk;
3813
0
    sk = NULL;
3814
    /* Ensure there is no RPK */
3815
0
    EVP_PKEY_free(s->session->peer_rpk);
3816
0
    s->session->peer_rpk = NULL;
3817
3818
    /*
3819
     * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3820
     * message
3821
     */
3822
0
    if (SSL_CONNECTION_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3823
        /* SSLfatal() already called */
3824
0
        goto err;
3825
0
    }
3826
3827
    /*
3828
     * Inconsistency alert: cert_chain does *not* include the peer's own
3829
     * certificate, while we do include it in statem_clnt.c
3830
     */
3831
3832
    /* Save the current hash state for when we receive the CertificateVerify */
3833
0
    if (SSL_CONNECTION_IS_TLS13(s)) {
3834
0
        if (!ssl_handshake_hash(s, s->cert_verify_hash,
3835
0
                sizeof(s->cert_verify_hash),
3836
0
                &s->cert_verify_hash_len)) {
3837
            /* SSLfatal() already called */
3838
0
            goto err;
3839
0
        }
3840
3841
        /* Resend session tickets */
3842
0
        s->sent_tickets = 0;
3843
0
    }
3844
3845
0
    ret = MSG_PROCESS_CONTINUE_READING;
3846
3847
0
err:
3848
0
    X509_free(x);
3849
0
    OSSL_STACK_OF_X509_free(sk);
3850
0
    return ret;
3851
0
}
3852
3853
#ifndef OPENSSL_NO_COMP_ALG
3854
MSG_PROCESS_RETURN tls_process_client_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)
3855
{
3856
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3857
    PACKET tmppkt;
3858
    BUF_MEM *buf = BUF_MEM_new();
3859
3860
    if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)
3861
        ret = tls_process_client_certificate(sc, &tmppkt);
3862
3863
    BUF_MEM_free(buf);
3864
    return ret;
3865
}
3866
#endif
3867
3868
CON_FUNC_RETURN tls_construct_server_certificate(SSL_CONNECTION *s, WPACKET *pkt)
3869
24.8k
{
3870
24.8k
    CERT_PKEY *cpk = s->s3.tmp.cert;
3871
3872
24.8k
    if (cpk == NULL) {
3873
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3874
0
        return CON_FUNC_ERROR;
3875
0
    }
3876
3877
    /*
3878
     * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3879
     * for the server Certificate message
3880
     */
3881
24.8k
    if (SSL_CONNECTION_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
3882
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3883
0
        return CON_FUNC_ERROR;
3884
0
    }
3885
24.8k
    switch (s->ext.server_cert_type) {
3886
0
    case TLSEXT_cert_type_rpk:
3887
0
        if (!tls_output_rpk(s, pkt, cpk)) {
3888
            /* SSLfatal() already called */
3889
0
            return 0;
3890
0
        }
3891
0
        break;
3892
24.8k
    case TLSEXT_cert_type_x509:
3893
24.8k
        if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {
3894
            /* SSLfatal() already called */
3895
0
            return 0;
3896
0
        }
3897
24.8k
        break;
3898
24.8k
    default:
3899
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3900
0
        return 0;
3901
24.8k
    }
3902
3903
24.8k
    return CON_FUNC_SUCCESS;
3904
24.8k
}
3905
3906
#ifndef OPENSSL_NO_COMP_ALG
3907
CON_FUNC_RETURN tls_construct_server_compressed_certificate(SSL_CONNECTION *sc, WPACKET *pkt)
3908
{
3909
    int alg = get_compressed_certificate_alg(sc);
3910
    OSSL_COMP_CERT *cc = sc->s3.tmp.cert->comp_cert[alg];
3911
3912
    if (!ossl_assert(cc != NULL)) {
3913
        SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3914
        return 0;
3915
    }
3916
    /*
3917
     * Server can't compress on-demand
3918
     * Use pre-compressed certificate
3919
     */
3920
    if (!WPACKET_put_bytes_u16(pkt, alg)
3921
        || !WPACKET_put_bytes_u24(pkt, cc->orig_len)
3922
        || !WPACKET_start_sub_packet_u24(pkt)
3923
        || !WPACKET_memcpy(pkt, cc->data, cc->len)
3924
        || !WPACKET_close(pkt))
3925
        return 0;
3926
3927
    sc->s3.tmp.cert->cert_comp_used++;
3928
    return 1;
3929
}
3930
#endif
3931
3932
static int create_ticket_prequel(SSL_CONNECTION *s, WPACKET *pkt,
3933
    uint32_t age_add, unsigned char *tick_nonce)
3934
97
{
3935
97
    uint32_t timeout = (uint32_t)ossl_time2seconds(s->session->timeout);
3936
3937
    /*
3938
     * Ticket lifetime hint:
3939
     * In TLSv1.3 we reset the "time" field above, and always specify the
3940
     * timeout, limited to a 1 week period per RFC8446.
3941
     * For TLSv1.2 this is advisory only and we leave this unspecified for
3942
     * resumed session (for simplicity).
3943
     */
3944
97
#define ONE_WEEK_SEC (7 * 24 * 60 * 60)
3945
3946
97
    if (SSL_CONNECTION_IS_TLS13(s)) {
3947
0
        if (ossl_time_compare(s->session->timeout,
3948
0
                ossl_seconds2time(ONE_WEEK_SEC))
3949
0
            > 0)
3950
0
            timeout = ONE_WEEK_SEC;
3951
97
    } else if (s->hit)
3952
0
        timeout = 0;
3953
3954
97
    if (!WPACKET_put_bytes_u32(pkt, timeout)) {
3955
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3956
0
        return 0;
3957
0
    }
3958
3959
97
    if (SSL_CONNECTION_IS_TLS13(s)) {
3960
0
        if (!WPACKET_put_bytes_u32(pkt, age_add)
3961
0
            || !WPACKET_sub_memcpy_u8(pkt, tick_nonce, TICKET_NONCE_SIZE)) {
3962
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3963
0
            return 0;
3964
0
        }
3965
0
    }
3966
3967
    /* Start the sub-packet for the actual ticket data */
3968
97
    if (!WPACKET_start_sub_packet_u16(pkt)) {
3969
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3970
0
        return 0;
3971
0
    }
3972
3973
97
    return 1;
3974
97
}
3975
3976
static CON_FUNC_RETURN construct_stateless_ticket(SSL_CONNECTION *s,
3977
    WPACKET *pkt,
3978
    uint32_t age_add,
3979
    unsigned char *tick_nonce)
3980
64
{
3981
64
    unsigned char *senc = NULL;
3982
64
    EVP_CIPHER_CTX *ctx = NULL;
3983
64
    SSL_HMAC *hctx = NULL;
3984
64
    unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3985
64
    const unsigned char *const_p;
3986
64
    int len, slen_full, slen, lenfinal;
3987
64
    SSL_SESSION *sess;
3988
64
    size_t hlen;
3989
64
    SSL_CTX *tctx = s->session_ctx;
3990
64
    unsigned char iv[EVP_MAX_IV_LENGTH];
3991
64
    unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3992
64
    int iv_len;
3993
64
    CON_FUNC_RETURN ok = CON_FUNC_ERROR;
3994
64
    size_t macoffset, macendoffset;
3995
64
    SSL *ssl = SSL_CONNECTION_GET_USER_SSL(s);
3996
64
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3997
3998
    /* get session encoding length */
3999
64
    slen_full = i2d_SSL_SESSION(s->session, NULL);
4000
    /*
4001
     * Some length values are 16 bits, so forget it if session is too
4002
     * long
4003
     */
4004
64
    if (slen_full == 0 || slen_full > 0xFF00) {
4005
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4006
0
        goto err;
4007
0
    }
4008
64
    senc = OPENSSL_malloc(slen_full);
4009
64
    if (senc == NULL) {
4010
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4011
0
        goto err;
4012
0
    }
4013
4014
64
    ctx = EVP_CIPHER_CTX_new();
4015
64
    if (ctx == NULL) {
4016
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
4017
0
        goto err;
4018
0
    }
4019
64
    hctx = ssl_hmac_new(tctx);
4020
64
    if (hctx == NULL) {
4021
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
4022
0
        goto err;
4023
0
    }
4024
4025
64
    p = senc;
4026
64
    if (!i2d_SSL_SESSION(s->session, &p)) {
4027
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4028
0
        goto err;
4029
0
    }
4030
4031
    /*
4032
     * create a fresh copy (not shared with other threads) to clean up
4033
     */
4034
64
    const_p = senc;
4035
64
    sess = d2i_SSL_SESSION_ex(NULL, &const_p, slen_full, sctx->libctx,
4036
64
        sctx->propq);
4037
64
    if (sess == NULL) {
4038
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4039
0
        goto err;
4040
0
    }
4041
4042
64
    slen = i2d_SSL_SESSION(sess, NULL);
4043
64
    if (slen == 0 || slen > slen_full) {
4044
        /* shouldn't ever happen */
4045
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4046
0
        SSL_SESSION_free(sess);
4047
0
        goto err;
4048
0
    }
4049
64
    p = senc;
4050
64
    if (!i2d_SSL_SESSION(sess, &p)) {
4051
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4052
0
        SSL_SESSION_free(sess);
4053
0
        goto err;
4054
0
    }
4055
64
    SSL_SESSION_free(sess);
4056
4057
    /*
4058
     * Initialize HMAC and cipher contexts. If callback present it does
4059
     * all the work otherwise use generated values from parent ctx.
4060
     */
4061
64
#ifndef OPENSSL_NO_DEPRECATED_3_0
4062
64
    if (tctx->ext.ticket_key_evp_cb != NULL || tctx->ext.ticket_key_cb != NULL)
4063
#else
4064
    if (tctx->ext.ticket_key_evp_cb != NULL)
4065
#endif
4066
0
    {
4067
0
        int ret = 0;
4068
4069
0
        if (tctx->ext.ticket_key_evp_cb != NULL)
4070
0
            ret = tctx->ext.ticket_key_evp_cb(ssl, key_name, iv, ctx,
4071
0
                ssl_hmac_get0_EVP_MAC_CTX(hctx),
4072
0
                1);
4073
0
#ifndef OPENSSL_NO_DEPRECATED_3_0
4074
0
        else if (tctx->ext.ticket_key_cb != NULL)
4075
            /* if 0 is returned, write an empty ticket */
4076
0
            ret = tctx->ext.ticket_key_cb(ssl, key_name, iv, ctx,
4077
0
                ssl_hmac_get0_HMAC_CTX(hctx), 1);
4078
0
#endif
4079
4080
0
        if (ret == 0) {
4081
            /*
4082
             * In TLSv1.2 we construct a 0 length ticket. In TLSv1.3 a 0
4083
             * length ticket is not allowed so we abort construction of the
4084
             * ticket
4085
             */
4086
0
            if (SSL_CONNECTION_IS_TLS13(s)) {
4087
0
                ok = CON_FUNC_DONT_SEND;
4088
0
                goto err;
4089
0
            }
4090
            /* Put timeout and length */
4091
0
            if (!WPACKET_put_bytes_u32(pkt, 0)
4092
0
                || !WPACKET_put_bytes_u16(pkt, 0)) {
4093
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4094
0
                goto err;
4095
0
            }
4096
0
            OPENSSL_free(senc);
4097
0
            EVP_CIPHER_CTX_free(ctx);
4098
0
            ssl_hmac_free(hctx);
4099
0
            return CON_FUNC_SUCCESS;
4100
0
        }
4101
0
        if (ret < 0) {
4102
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
4103
0
            goto err;
4104
0
        }
4105
0
        iv_len = EVP_CIPHER_CTX_get_iv_length(ctx);
4106
0
        if (iv_len < 0) {
4107
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4108
0
            goto err;
4109
0
        }
4110
64
    } else {
4111
64
        EVP_CIPHER *cipher = EVP_CIPHER_fetch(sctx->libctx, "AES-256-CBC",
4112
64
            sctx->propq);
4113
4114
64
        if (cipher == NULL) {
4115
            /* Error is already recorded */
4116
0
            SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
4117
0
            goto err;
4118
0
        }
4119
4120
64
        iv_len = EVP_CIPHER_get_iv_length(cipher);
4121
64
        if (iv_len < 0
4122
64
            || RAND_bytes_ex(sctx->libctx, iv, iv_len, 0) <= 0
4123
64
            || !EVP_EncryptInit_ex(ctx, cipher, NULL,
4124
64
                tctx->ext.secure->tick_aes_key, iv)
4125
64
            || !ssl_hmac_init(hctx, tctx->ext.secure->tick_hmac_key,
4126
64
                sizeof(tctx->ext.secure->tick_hmac_key),
4127
64
                "SHA256")) {
4128
0
            EVP_CIPHER_free(cipher);
4129
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4130
0
            goto err;
4131
0
        }
4132
64
        EVP_CIPHER_free(cipher);
4133
64
        memcpy(key_name, tctx->ext.tick_key_name,
4134
64
            sizeof(tctx->ext.tick_key_name));
4135
64
    }
4136
4137
64
    if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4138
        /* SSLfatal() already called */
4139
0
        goto err;
4140
0
    }
4141
4142
64
    if (!WPACKET_get_total_written(pkt, &macoffset)
4143
        /* Output key name */
4144
64
        || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
4145
        /* output IV */
4146
64
        || !WPACKET_memcpy(pkt, iv, iv_len)
4147
64
        || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
4148
64
            &encdata1)
4149
        /* Encrypt session data */
4150
64
        || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
4151
64
        || !WPACKET_allocate_bytes(pkt, len, &encdata2)
4152
64
        || encdata1 != encdata2
4153
64
        || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
4154
64
        || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
4155
64
        || encdata1 + len != encdata2
4156
64
        || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
4157
64
        || !WPACKET_get_total_written(pkt, &macendoffset)
4158
64
        || !ssl_hmac_update(hctx,
4159
64
            (unsigned char *)s->init_buf->data + macoffset,
4160
64
            macendoffset - macoffset)
4161
64
        || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
4162
64
        || !ssl_hmac_final(hctx, macdata1, &hlen, EVP_MAX_MD_SIZE)
4163
64
        || hlen > EVP_MAX_MD_SIZE
4164
64
        || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
4165
64
        || macdata1 != macdata2) {
4166
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4167
0
        goto err;
4168
0
    }
4169
4170
    /* Close the sub-packet created by create_ticket_prequel() */
4171
64
    if (!WPACKET_close(pkt)) {
4172
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4173
0
        goto err;
4174
0
    }
4175
4176
64
    ok = CON_FUNC_SUCCESS;
4177
64
err:
4178
64
    OPENSSL_free(senc);
4179
64
    EVP_CIPHER_CTX_free(ctx);
4180
64
    ssl_hmac_free(hctx);
4181
64
    return ok;
4182
64
}
4183
4184
static int construct_stateful_ticket(SSL_CONNECTION *s, WPACKET *pkt,
4185
    uint32_t age_add,
4186
    unsigned char *tick_nonce)
4187
0
{
4188
0
    if (!create_ticket_prequel(s, pkt, age_add, tick_nonce)) {
4189
        /* SSLfatal() already called */
4190
0
        return 0;
4191
0
    }
4192
4193
0
    if (!WPACKET_memcpy(pkt, s->session->session_id,
4194
0
            s->session->session_id_length)
4195
0
        || !WPACKET_close(pkt)) {
4196
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4197
0
        return 0;
4198
0
    }
4199
4200
0
    return 1;
4201
0
}
4202
4203
static void tls_update_ticket_counts(SSL_CONNECTION *s)
4204
0
{
4205
    /*
4206
     * Increment both |sent_tickets| and |next_ticket_nonce|. |sent_tickets|
4207
     * gets reset to 0 if we send more tickets following a post-handshake
4208
     * auth, but |next_ticket_nonce| does not.  If we're sending extra
4209
     * tickets, decrement the count of pending extra tickets.
4210
     */
4211
0
    s->sent_tickets++;
4212
0
    s->next_ticket_nonce++;
4213
0
    if (s->ext.extra_tickets_expected > 0)
4214
0
        s->ext.extra_tickets_expected--;
4215
0
}
4216
4217
CON_FUNC_RETURN tls_construct_new_session_ticket(SSL_CONNECTION *s, WPACKET *pkt)
4218
92
{
4219
92
    SSL_CTX *tctx = s->session_ctx;
4220
92
    unsigned char tick_nonce[TICKET_NONCE_SIZE];
4221
92
    union {
4222
92
        unsigned char age_add_c[sizeof(uint32_t)];
4223
92
        uint32_t age_add;
4224
92
    } age_add_u;
4225
92
    CON_FUNC_RETURN ret = CON_FUNC_ERROR;
4226
4227
92
    age_add_u.age_add = 0;
4228
4229
92
    if (SSL_CONNECTION_IS_TLS13(s)) {
4230
0
        size_t i, hashlen;
4231
0
        uint64_t nonce;
4232
        /* ASCII: "resumption", in hex for EBCDIC compatibility */
4233
0
        static const unsigned char nonce_label[] = { 0x72, 0x65, 0x73, 0x75, 0x6D,
4234
0
            0x70, 0x74, 0x69, 0x6F, 0x6E };
4235
0
        const EVP_MD *md = ssl_handshake_md(s);
4236
0
        int hashleni = EVP_MD_get_size(md);
4237
4238
        /* Ensure cast to size_t is safe */
4239
0
        if (!ossl_assert(hashleni > 0)) {
4240
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4241
0
            goto err;
4242
0
        }
4243
0
        hashlen = (size_t)hashleni;
4244
4245
        /*
4246
         * If we already sent one NewSessionTicket, or we resumed then
4247
         * s->session may already be in a cache and so we must not modify it.
4248
         * Instead we need to take a copy of it and modify that.
4249
         */
4250
0
        if (s->sent_tickets != 0 || s->hit) {
4251
0
            SSL_SESSION *new_sess = ssl_session_dup(s->session, 0);
4252
4253
0
            if (new_sess == NULL) {
4254
                /* SSLfatal already called */
4255
0
                goto err;
4256
0
            }
4257
4258
0
            SSL_SESSION_free(s->session);
4259
0
            s->session = new_sess;
4260
0
        }
4261
4262
0
        if (!ssl_generate_session_id(s, s->session)) {
4263
            /* SSLfatal() already called */
4264
0
            goto err;
4265
0
        }
4266
0
        if (RAND_bytes_ex(SSL_CONNECTION_GET_CTX(s)->libctx,
4267
0
                age_add_u.age_add_c, sizeof(age_add_u), 0)
4268
0
            <= 0) {
4269
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4270
0
            goto err;
4271
0
        }
4272
0
        s->session->ext.tick_age_add = age_add_u.age_add;
4273
4274
0
        nonce = s->next_ticket_nonce;
4275
0
        for (i = TICKET_NONCE_SIZE; i > 0; i--) {
4276
0
            tick_nonce[i - 1] = (unsigned char)(nonce & 0xff);
4277
0
            nonce >>= 8;
4278
0
        }
4279
4280
0
        if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
4281
0
                nonce_label,
4282
0
                sizeof(nonce_label),
4283
0
                tick_nonce,
4284
0
                TICKET_NONCE_SIZE,
4285
0
                s->session->master_key,
4286
0
                hashlen, 1)) {
4287
            /* SSLfatal() already called */
4288
0
            goto err;
4289
0
        }
4290
0
        s->session->master_key_length = hashlen;
4291
4292
0
        s->session->time = ossl_time_now();
4293
0
        ssl_session_calculate_timeout(s->session);
4294
0
        if (s->s3.alpn_selected != NULL) {
4295
0
            OPENSSL_free(s->session->ext.alpn_selected);
4296
0
            s->session->ext.alpn_selected = OPENSSL_memdup(s->s3.alpn_selected, s->s3.alpn_selected_len);
4297
0
            if (s->session->ext.alpn_selected == NULL) {
4298
0
                s->session->ext.alpn_selected_len = 0;
4299
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
4300
0
                goto err;
4301
0
            }
4302
0
            s->session->ext.alpn_selected_len = s->s3.alpn_selected_len;
4303
0
        }
4304
0
        s->session->ext.max_early_data = s->max_early_data;
4305
0
    }
4306
4307
92
    if (tctx->generate_ticket_cb != NULL && tctx->generate_ticket_cb(SSL_CONNECTION_GET_USER_SSL(s), tctx->ticket_cb_data) == 0) {
4308
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4309
0
        goto err;
4310
0
    }
4311
    /*
4312
     * If we are using anti-replay protection then we behave as if
4313
     * SSL_OP_NO_TICKET is set - we are caching tickets anyway so there
4314
     * is no point in using full stateless tickets.
4315
     */
4316
92
    if (SSL_CONNECTION_IS_TLS13(s)
4317
0
        && ((s->options & SSL_OP_NO_TICKET) != 0
4318
0
            || (s->max_early_data > 0
4319
0
                && (s->options & SSL_OP_NO_ANTI_REPLAY) == 0))) {
4320
0
        if (!construct_stateful_ticket(s, pkt, age_add_u.age_add, tick_nonce)) {
4321
            /* SSLfatal() already called */
4322
0
            goto err;
4323
0
        }
4324
92
    } else {
4325
92
        CON_FUNC_RETURN tmpret;
4326
4327
92
        tmpret = construct_stateless_ticket(s, pkt, age_add_u.age_add,
4328
92
            tick_nonce);
4329
92
        if (tmpret != CON_FUNC_SUCCESS) {
4330
0
            if (tmpret == CON_FUNC_DONT_SEND) {
4331
                /* Non-fatal. Abort construction but continue */
4332
0
                ret = CON_FUNC_DONT_SEND;
4333
                /* We count this as a success so update the counts anwyay */
4334
0
                tls_update_ticket_counts(s);
4335
0
            }
4336
            /* else SSLfatal() already called */
4337
0
            goto err;
4338
0
        }
4339
92
    }
4340
4341
92
    if (SSL_CONNECTION_IS_TLS13(s)) {
4342
0
        if (!tls_construct_extensions(s, pkt,
4343
0
                SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
4344
0
                NULL, 0)) {
4345
            /* SSLfatal() already called */
4346
0
            goto err;
4347
0
        }
4348
0
        tls_update_ticket_counts(s);
4349
0
        ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
4350
0
    }
4351
4352
92
    ret = CON_FUNC_SUCCESS;
4353
92
err:
4354
92
    return ret;
4355
92
}
4356
4357
/*
4358
 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
4359
 * create a separate message. Returns 1 on success or 0 on failure.
4360
 */
4361
int tls_construct_cert_status_body(SSL_CONNECTION *s, WPACKET *pkt)
4362
0
{
4363
0
    if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
4364
0
        || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
4365
0
            s->ext.ocsp.resp_len)) {
4366
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4367
0
        return 0;
4368
0
    }
4369
4370
0
    return 1;
4371
0
}
4372
4373
CON_FUNC_RETURN tls_construct_cert_status(SSL_CONNECTION *s, WPACKET *pkt)
4374
0
{
4375
0
    if (!tls_construct_cert_status_body(s, pkt)) {
4376
        /* SSLfatal() already called */
4377
0
        return CON_FUNC_ERROR;
4378
0
    }
4379
4380
0
    return CON_FUNC_SUCCESS;
4381
0
}
4382
4383
#ifndef OPENSSL_NO_NEXTPROTONEG
4384
/*
4385
 * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
4386
 * It sets the next_proto member in s if found
4387
 */
4388
MSG_PROCESS_RETURN tls_process_next_proto(SSL_CONNECTION *s, PACKET *pkt)
4389
0
{
4390
0
    PACKET next_proto, padding;
4391
0
    size_t next_proto_len;
4392
4393
    /*-
4394
     * The payload looks like:
4395
     *   uint8 proto_len;
4396
     *   uint8 proto[proto_len];
4397
     *   uint8 padding_len;
4398
     *   uint8 padding[padding_len];
4399
     */
4400
0
    if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
4401
0
        || !PACKET_get_length_prefixed_1(pkt, &padding)
4402
0
        || PACKET_remaining(pkt) > 0) {
4403
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4404
0
        return MSG_PROCESS_ERROR;
4405
0
    }
4406
4407
0
    if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
4408
0
        s->ext.npn_len = 0;
4409
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4410
0
        return MSG_PROCESS_ERROR;
4411
0
    }
4412
4413
0
    s->ext.npn_len = (unsigned char)next_proto_len;
4414
4415
0
    return MSG_PROCESS_CONTINUE_READING;
4416
0
}
4417
#endif
4418
4419
static CON_FUNC_RETURN tls_construct_encrypted_extensions(SSL_CONNECTION *s,
4420
    WPACKET *pkt)
4421
2.95k
{
4422
2.95k
    if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4423
2.95k
            NULL, 0)) {
4424
        /* SSLfatal() already called */
4425
0
        return CON_FUNC_ERROR;
4426
0
    }
4427
4428
2.95k
    return CON_FUNC_SUCCESS;
4429
2.95k
}
4430
4431
MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL_CONNECTION *s, PACKET *pkt)
4432
0
{
4433
0
    if (PACKET_remaining(pkt) != 0) {
4434
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4435
0
        return MSG_PROCESS_ERROR;
4436
0
    }
4437
4438
0
    if (s->early_data_state != SSL_EARLY_DATA_READING
4439
0
        && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
4440
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4441
0
        return MSG_PROCESS_ERROR;
4442
0
    }
4443
4444
    /*
4445
     * EndOfEarlyData signals a key change so the end of the message must be on
4446
     * a record boundary.
4447
     */
4448
0
    if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
4449
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_NOT_ON_RECORD_BOUNDARY);
4450
0
        return MSG_PROCESS_ERROR;
4451
0
    }
4452
4453
0
    s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
4454
0
    if (!SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->change_cipher_state(s,
4455
0
            SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
4456
        /* SSLfatal() already called */
4457
0
        return MSG_PROCESS_ERROR;
4458
0
    }
4459
4460
0
    return MSG_PROCESS_CONTINUE_READING;
4461
0
}