Coverage Report

Created: 2026-05-24 07:14

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