Coverage Report

Created: 2025-12-31 06:58

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