Coverage Report

Created: 2025-08-28 07:07

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