Coverage Report

Created: 2025-12-04 06:33

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl36/ssl/statem/statem_clnt.c
Line
Count
Source
1
/*
2
 * Copyright 1995-2025 The OpenSSL Project Authors. All Rights Reserved.
3
 * Copyright (c) 2002, Oracle and/or its affiliates. All rights reserved
4
 * Copyright 2005 Nokia. All rights reserved.
5
 *
6
 * Licensed under the Apache License 2.0 (the "License").  You may not use
7
 * this file except in compliance with the License.  You can obtain a copy
8
 * in the file LICENSE in the source distribution or at
9
 * https://www.openssl.org/source/license.html
10
 */
11
12
#include <stdio.h>
13
#include <time.h>
14
#include <assert.h>
15
#include "../ssl_local.h"
16
#include "statem_local.h"
17
#include <openssl/buffer.h>
18
#include <openssl/rand.h>
19
#include <openssl/objects.h>
20
#include <openssl/evp.h>
21
#include <openssl/md5.h>
22
#include <openssl/dh.h>
23
#include <openssl/rsa.h>
24
#include <openssl/bn.h>
25
#include <openssl/engine.h>
26
#include <openssl/trace.h>
27
#include <openssl/core_names.h>
28
#include <openssl/param_build.h>
29
#include "internal/cryptlib.h"
30
#include "internal/comp.h"
31
#include "internal/ssl_unwrap.h"
32
#include <openssl/ocsp.h>
33
34
static MSG_PROCESS_RETURN tls_process_as_hello_retry_request(SSL_CONNECTION *s,
35
                                                             PACKET *pkt);
36
static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL_CONNECTION *s,
37
                                                           PACKET *pkt);
38
39
static ossl_inline int cert_req_allowed(SSL_CONNECTION *s);
40
static int key_exchange_expected(SSL_CONNECTION *s);
41
static int ssl_cipher_list_to_bytes(SSL_CONNECTION *s, STACK_OF(SSL_CIPHER) *sk,
42
                                    WPACKET *pkt);
43
44
static ossl_inline int received_server_cert(SSL_CONNECTION *sc)
45
5.13k
{
46
5.13k
    return sc->session->peer_rpk != NULL || sc->session->peer != NULL;
47
5.13k
}
48
49
/*
50
 * Is a CertificateRequest message allowed at the moment or not?
51
 *
52
 *  Return values are:
53
 *  1: Yes
54
 *  0: No
55
 */
56
static ossl_inline int cert_req_allowed(SSL_CONNECTION *s)
57
764
{
58
    /* TLS does not like anon-DH with client cert */
59
764
    if ((s->version > SSL3_VERSION
60
732
         && (s->s3.tmp.new_cipher->algorithm_auth & SSL_aNULL))
61
749
        || (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aSRP | SSL_aPSK)))
62
15
        return 0;
63
64
749
    return 1;
65
764
}
66
67
/*
68
 * Should we expect the ServerKeyExchange message or not?
69
 *
70
 *  Return values are:
71
 *  1: Yes
72
 *  0: No
73
 */
74
static int key_exchange_expected(SSL_CONNECTION *s)
75
25.8k
{
76
25.8k
    long alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
77
78
    /*
79
     * Can't skip server key exchange if this is an ephemeral
80
     * ciphersuite or for SRP
81
     */
82
25.8k
    if (alg_k & (SSL_kDHE | SSL_kECDHE | SSL_kDHEPSK | SSL_kECDHEPSK
83
25.8k
                 | SSL_kSRP)) {
84
19.7k
        return 1;
85
19.7k
    }
86
87
6.16k
    return 0;
88
25.8k
}
89
90
/*
91
 * ossl_statem_client_read_transition() encapsulates the logic for the allowed
92
 * handshake state transitions when a TLS1.3 client is reading messages from the
93
 * server. The message type that the server has sent is provided in |mt|. The
94
 * current state is in |s->statem.hand_state|.
95
 *
96
 * Return values are 1 for success (transition allowed) and  0 on error
97
 * (transition not allowed)
98
 */
99
static int ossl_statem_client13_read_transition(SSL_CONNECTION *s, int mt)
100
88.4k
{
101
88.4k
    OSSL_STATEM *st = &s->statem;
102
103
    /*
104
     * Note: There is no case for TLS_ST_CW_CLNT_HELLO, because we haven't
105
     * yet negotiated TLSv1.3 at that point so that is handled by
106
     * ossl_statem_client_read_transition()
107
     */
108
109
88.4k
    switch (st->hand_state) {
110
0
    default:
111
0
        break;
112
113
0
    case TLS_ST_CW_CLNT_HELLO:
114
        /*
115
         * This must a ClientHello following a HelloRetryRequest, so the only
116
         * thing we can get now is a ServerHello.
117
         */
118
0
        if (mt == SSL3_MT_SERVER_HELLO) {
119
0
            st->hand_state = TLS_ST_CR_SRVR_HELLO;
120
0
            return 1;
121
0
        }
122
0
        break;
123
124
23.4k
    case TLS_ST_CR_SRVR_HELLO:
125
23.4k
        if (mt == SSL3_MT_ENCRYPTED_EXTENSIONS) {
126
23.2k
            st->hand_state = TLS_ST_CR_ENCRYPTED_EXTENSIONS;
127
23.2k
            return 1;
128
23.2k
        }
129
187
        break;
130
131
21.8k
    case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
132
21.8k
        if (s->hit) {
133
0
            if (mt == SSL3_MT_FINISHED) {
134
0
                st->hand_state = TLS_ST_CR_FINISHED;
135
0
                return 1;
136
0
            }
137
21.8k
        } else {
138
21.8k
            if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
139
186
                st->hand_state = TLS_ST_CR_CERT_REQ;
140
186
                return 1;
141
186
            }
142
21.6k
            if (mt == SSL3_MT_CERTIFICATE) {
143
21.6k
                st->hand_state = TLS_ST_CR_CERT;
144
21.6k
                return 1;
145
21.6k
            }
146
#ifndef OPENSSL_NO_COMP_ALG
147
            if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
148
                    && s->ext.compress_certificate_sent) {
149
                st->hand_state = TLS_ST_CR_COMP_CERT;
150
                return 1;
151
            }
152
#endif
153
21.6k
        }
154
26
        break;
155
156
26
    case TLS_ST_CR_CERT_REQ:
157
0
        if (mt == SSL3_MT_CERTIFICATE) {
158
0
            st->hand_state = TLS_ST_CR_CERT;
159
0
            return 1;
160
0
        }
161
#ifndef OPENSSL_NO_COMP_ALG
162
        if (mt == SSL3_MT_COMPRESSED_CERTIFICATE
163
                && s->ext.compress_certificate_sent) {
164
            st->hand_state = TLS_ST_CR_COMP_CERT;
165
            return 1;
166
        }
167
#endif
168
0
        break;
169
170
18.4k
    case TLS_ST_CR_CERT:
171
18.4k
    case TLS_ST_CR_COMP_CERT:
172
18.4k
        if (mt == SSL3_MT_CERTIFICATE_VERIFY) {
173
18.0k
            st->hand_state = TLS_ST_CR_CERT_VRFY;
174
18.0k
            return 1;
175
18.0k
        }
176
357
        break;
177
178
17.2k
    case TLS_ST_CR_CERT_VRFY:
179
17.2k
        if (mt == SSL3_MT_FINISHED) {
180
13.5k
            st->hand_state = TLS_ST_CR_FINISHED;
181
13.5k
            return 1;
182
13.5k
        }
183
3.71k
        break;
184
185
7.36k
    case TLS_ST_OK:
186
7.36k
        if (mt == SSL3_MT_NEWSESSION_TICKET) {
187
7.16k
            st->hand_state = TLS_ST_CR_SESSION_TICKET;
188
7.16k
            return 1;
189
7.16k
        }
190
202
        if (mt == SSL3_MT_KEY_UPDATE && !SSL_IS_QUIC_HANDSHAKE(s)) {
191
0
            st->hand_state = TLS_ST_CR_KEY_UPDATE;
192
0
            return 1;
193
0
        }
194
202
        if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
195
#if DTLS_MAX_VERSION_INTERNAL != DTLS1_2_VERSION
196
            /* Restore digest for PHA before adding message.*/
197
# error Internal DTLS version error
198
#endif
199
6
            if (!SSL_CONNECTION_IS_DTLS(s)
200
6
                && s->post_handshake_auth == SSL_PHA_EXT_SENT) {
201
0
                s->post_handshake_auth = SSL_PHA_REQUESTED;
202
                /*
203
                 * In TLS, this is called before the message is added to the
204
                 * digest. In DTLS, this is expected to be called after adding
205
                 * to the digest. Either move the digest restore, or add the
206
                 * message here after the swap, or do it after the clientFinished?
207
                 */
208
0
                if (!tls13_restore_handshake_digest_for_pha(s)) {
209
                    /* SSLfatal() already called */
210
0
                    return 0;
211
0
                }
212
0
                st->hand_state = TLS_ST_CR_CERT_REQ;
213
0
                return 1;
214
0
            }
215
6
        }
216
202
        break;
217
88.4k
    }
218
219
    /* No valid transition found */
220
4.48k
    return 0;
221
88.4k
}
222
223
/*
224
 * ossl_statem_client_read_transition() encapsulates the logic for the allowed
225
 * handshake state transitions when the client is reading messages from the
226
 * server. The message type that the server has sent is provided in |mt|. The
227
 * current state is in |s->statem.hand_state|.
228
 *
229
 * Return values are 1 for success (transition allowed) and  0 on error
230
 * (transition not allowed)
231
 */
232
int ossl_statem_client_read_transition(SSL_CONNECTION *s, int mt)
233
235k
{
234
235k
    OSSL_STATEM *st = &s->statem;
235
235k
    int ske_expected;
236
237
    /*
238
     * Note that after writing the first ClientHello we don't know what version
239
     * we are going to negotiate yet, so we don't take this branch until later.
240
     */
241
235k
    if (SSL_CONNECTION_IS_TLS13(s)) {
242
88.4k
        if (!ossl_statem_client13_read_transition(s, mt))
243
4.48k
            goto err;
244
83.9k
        return 1;
245
88.4k
    }
246
247
147k
    switch (st->hand_state) {
248
0
    default:
249
0
        break;
250
251
80.1k
    case TLS_ST_CW_CLNT_HELLO:
252
80.1k
        if (mt == SSL3_MT_SERVER_HELLO) {
253
75.5k
            st->hand_state = TLS_ST_CR_SRVR_HELLO;
254
75.5k
            return 1;
255
75.5k
        }
256
257
4.62k
        if (SSL_CONNECTION_IS_DTLS(s)) {
258
3.99k
            if (mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
259
3.81k
                st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
260
3.81k
                return 1;
261
3.81k
            }
262
3.99k
        }
263
808
        break;
264
265
808
    case TLS_ST_EARLY_DATA:
266
        /*
267
         * We've not actually selected TLSv1.3 yet, but we have sent early
268
         * data. The only thing allowed now is a ServerHello or a
269
         * HelloRetryRequest.
270
         */
271
0
        if (mt == SSL3_MT_SERVER_HELLO) {
272
0
            st->hand_state = TLS_ST_CR_SRVR_HELLO;
273
0
            return 1;
274
0
        }
275
0
        break;
276
277
40.0k
    case TLS_ST_CR_SRVR_HELLO:
278
40.0k
        if (s->hit) {
279
0
            if (s->ext.ticket_expected) {
280
0
                if (mt == SSL3_MT_NEWSESSION_TICKET) {
281
0
                    st->hand_state = TLS_ST_CR_SESSION_TICKET;
282
0
                    return 1;
283
0
                }
284
0
            } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
285
0
                st->hand_state = TLS_ST_CR_CHANGE;
286
0
                return 1;
287
0
            }
288
40.0k
        } else {
289
40.0k
            if (SSL_CONNECTION_IS_DTLS(s)
290
11.1k
                && mt == DTLS1_MT_HELLO_VERIFY_REQUEST) {
291
304
                st->hand_state = DTLS_ST_CR_HELLO_VERIFY_REQUEST;
292
304
                return 1;
293
39.7k
            } else if (s->version >= TLS1_VERSION
294
38.6k
                       && s->ext.session_secret_cb != NULL
295
0
                       && s->session->ext.tick != NULL
296
0
                       && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
297
                /*
298
                 * Normally, we can tell if the server is resuming the session
299
                 * from the session ID. EAP-FAST (RFC 4851), however, relies on
300
                 * the next server message after the ServerHello to determine if
301
                 * the server is resuming.
302
                 */
303
0
                s->hit = 1;
304
0
                st->hand_state = TLS_ST_CR_CHANGE;
305
0
                return 1;
306
39.7k
            } else if (!(s->s3.tmp.new_cipher->algorithm_auth
307
39.7k
                         & (SSL_aNULL | SSL_aSRP | SSL_aPSK))) {
308
27.7k
                if (mt == SSL3_MT_CERTIFICATE) {
309
27.7k
                    st->hand_state = TLS_ST_CR_CERT;
310
27.7k
                    return 1;
311
27.7k
                }
312
27.7k
            } else {
313
12.0k
                ske_expected = key_exchange_expected(s);
314
                /* SKE is optional for some PSK ciphersuites */
315
12.0k
                if (ske_expected
316
0
                    || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)
317
12.0k
                        && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
318
12.0k
                    if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
319
11.9k
                        st->hand_state = TLS_ST_CR_KEY_EXCH;
320
11.9k
                        return 1;
321
11.9k
                    }
322
12.0k
                } else if (mt == SSL3_MT_CERTIFICATE_REQUEST
323
0
                           && cert_req_allowed(s)) {
324
0
                    st->hand_state = TLS_ST_CR_CERT_REQ;
325
0
                    return 1;
326
0
                } else if (mt == SSL3_MT_SERVER_DONE) {
327
0
                    st->hand_state = TLS_ST_CR_SRVR_DONE;
328
0
                    return 1;
329
0
                }
330
12.0k
            }
331
40.0k
        }
332
121
        break;
333
334
11.1k
    case TLS_ST_CR_CERT:
335
11.1k
    case TLS_ST_CR_COMP_CERT:
336
        /*
337
         * The CertificateStatus message is optional even if
338
         * |ext.status_expected| is set
339
         */
340
11.1k
        if (s->ext.status_expected && mt == SSL3_MT_CERTIFICATE_STATUS) {
341
0
            st->hand_state = TLS_ST_CR_CERT_STATUS;
342
0
            return 1;
343
0
        }
344
        /* Fall through */
345
346
11.1k
    case TLS_ST_CR_CERT_STATUS:
347
11.1k
        ske_expected = key_exchange_expected(s);
348
        /* SKE is optional for some PSK ciphersuites */
349
11.1k
        if (ske_expected || ((s->s3.tmp.new_cipher->algorithm_mkey & SSL_PSK)
350
5.38k
                             && mt == SSL3_MT_SERVER_KEY_EXCHANGE)) {
351
5.38k
            if (mt == SSL3_MT_SERVER_KEY_EXCHANGE) {
352
5.28k
                st->hand_state = TLS_ST_CR_KEY_EXCH;
353
5.28k
                return 1;
354
5.28k
            }
355
102
            goto err;
356
5.38k
        }
357
        /* Fall through */
358
359
13.3k
    case TLS_ST_CR_KEY_EXCH:
360
13.3k
        if (mt == SSL3_MT_CERTIFICATE_REQUEST) {
361
665
            if (cert_req_allowed(s)) {
362
651
                st->hand_state = TLS_ST_CR_CERT_REQ;
363
651
                return 1;
364
651
            }
365
14
            goto err;
366
665
        }
367
        /* Fall through */
368
369
12.6k
    case TLS_ST_CR_CERT_REQ:
370
12.6k
        if (mt == SSL3_MT_SERVER_DONE) {
371
12.2k
            st->hand_state = TLS_ST_CR_SRVR_DONE;
372
12.2k
            return 1;
373
12.2k
        }
374
438
        break;
375
376
4.76k
    case TLS_ST_CW_FINISHED:
377
4.76k
        if (s->ext.ticket_expected) {
378
341
            if (mt == SSL3_MT_NEWSESSION_TICKET) {
379
320
                st->hand_state = TLS_ST_CR_SESSION_TICKET;
380
320
                return 1;
381
320
            }
382
4.42k
        } else if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
383
4.34k
            st->hand_state = TLS_ST_CR_CHANGE;
384
4.34k
            return 1;
385
4.34k
        }
386
98
        break;
387
388
183
    case TLS_ST_CR_SESSION_TICKET:
389
183
        if (mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
390
164
            st->hand_state = TLS_ST_CR_CHANGE;
391
164
            return 1;
392
164
        }
393
19
        break;
394
395
2.00k
    case TLS_ST_CR_CHANGE:
396
2.00k
        if (mt == SSL3_MT_FINISHED) {
397
1.74k
            st->hand_state = TLS_ST_CR_FINISHED;
398
1.74k
            return 1;
399
1.74k
        }
400
255
        break;
401
402
1.46k
    case TLS_ST_OK:
403
1.46k
        if (mt == SSL3_MT_HELLO_REQUEST) {
404
1.38k
            st->hand_state = TLS_ST_CR_HELLO_REQ;
405
1.38k
            return 1;
406
1.38k
        }
407
77
        break;
408
147k
    }
409
410
6.41k
 err:
411
    /* No valid transition found */
412
6.41k
    if (SSL_CONNECTION_IS_DTLS(s) && mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
413
8
        BIO *rbio;
414
415
        /*
416
         * CCS messages don't have a message sequence number so this is probably
417
         * because of an out-of-order CCS. We'll just drop it.
418
         */
419
8
        s->init_num = 0;
420
8
        s->rwstate = SSL_READING;
421
8
        rbio = SSL_get_rbio(SSL_CONNECTION_GET_SSL(s));
422
8
        BIO_clear_retry_flags(rbio);
423
8
        BIO_set_retry_read(rbio);
424
8
        return 0;
425
8
    }
426
6.41k
    SSLfatal(s, SSL3_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
427
6.41k
    return 0;
428
6.41k
}
429
430
static int do_compressed_cert(SSL_CONNECTION *sc)
431
0
{
432
    /* If we negotiated RPK, we won't try to compress it */
433
0
    return sc->ext.client_cert_type == TLSEXT_cert_type_x509
434
0
        && sc->ext.compress_certificate_from_peer[0] != TLSEXT_comp_cert_none;
435
0
}
436
437
/*
438
 * ossl_statem_client13_write_transition() works out what handshake state to
439
 * move to next when the TLSv1.3 client is writing messages to be sent to the
440
 * server.
441
 */
442
static WRITE_TRAN ossl_statem_client13_write_transition(SSL_CONNECTION *s)
443
15.7k
{
444
15.7k
    OSSL_STATEM *st = &s->statem;
445
446
    /*
447
     * Note: There are no cases for TLS_ST_BEFORE because we haven't negotiated
448
     * TLSv1.3 yet at that point. They are handled by
449
     * ossl_statem_client_write_transition().
450
     */
451
15.7k
    switch (st->hand_state) {
452
0
    default:
453
        /* Shouldn't happen */
454
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
455
0
        return WRITE_TRAN_ERROR;
456
457
0
    case TLS_ST_CR_CERT_REQ:
458
0
        if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
459
0
            if (do_compressed_cert(s))
460
0
                st->hand_state = TLS_ST_CW_COMP_CERT;
461
0
            else
462
0
                st->hand_state = TLS_ST_CW_CERT;
463
0
            return WRITE_TRAN_CONTINUE;
464
0
        }
465
        /*
466
         * We should only get here if we received a CertificateRequest after
467
         * we already sent close_notify
468
         */
469
0
        if (!ossl_assert((s->shutdown & SSL_SENT_SHUTDOWN) != 0)) {
470
            /* Shouldn't happen - same as default case */
471
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
472
0
            return WRITE_TRAN_ERROR;
473
0
        }
474
0
        st->hand_state = TLS_ST_OK;
475
0
        return WRITE_TRAN_CONTINUE;
476
477
5.81k
    case TLS_ST_CR_FINISHED:
478
5.81k
        if (s->early_data_state == SSL_EARLY_DATA_WRITE_RETRY
479
5.81k
                || s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING)
480
0
            st->hand_state = TLS_ST_PENDING_EARLY_DATA_END;
481
5.81k
        else if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
482
0
                 && s->hello_retry_request == SSL_HRR_NONE)
483
0
            st->hand_state = TLS_ST_CW_CHANGE;
484
5.81k
        else if (s->s3.tmp.cert_req == 0)
485
5.81k
            st->hand_state = TLS_ST_CW_FINISHED;
486
0
        else if (do_compressed_cert(s))
487
0
            st->hand_state = TLS_ST_CW_COMP_CERT;
488
0
        else
489
0
            st->hand_state = TLS_ST_CW_CERT;
490
491
5.81k
        s->ts_msg_read = ossl_time_now();
492
5.81k
        return WRITE_TRAN_CONTINUE;
493
494
0
    case TLS_ST_PENDING_EARLY_DATA_END:
495
0
        if (s->ext.early_data == SSL_EARLY_DATA_ACCEPTED && !SSL_NO_EOED(s)) {
496
0
            st->hand_state = TLS_ST_CW_END_OF_EARLY_DATA;
497
0
            return WRITE_TRAN_CONTINUE;
498
0
        }
499
        /* Fall through */
500
501
0
    case TLS_ST_CW_END_OF_EARLY_DATA:
502
0
    case TLS_ST_CW_CHANGE:
503
0
        if (s->s3.tmp.cert_req == 0)
504
0
            st->hand_state = TLS_ST_CW_FINISHED;
505
0
        else if (do_compressed_cert(s))
506
0
            st->hand_state = TLS_ST_CW_COMP_CERT;
507
0
        else
508
0
            st->hand_state = TLS_ST_CW_CERT;
509
0
        return WRITE_TRAN_CONTINUE;
510
511
0
    case TLS_ST_CW_COMP_CERT:
512
0
    case TLS_ST_CW_CERT:
513
        /* If a non-empty Certificate we also send CertificateVerify */
514
0
        st->hand_state = (s->s3.tmp.cert_req == 1) ? TLS_ST_CW_CERT_VRFY
515
0
                                                    : TLS_ST_CW_FINISHED;
516
0
        return WRITE_TRAN_CONTINUE;
517
518
0
    case TLS_ST_CW_CERT_VRFY:
519
0
        st->hand_state = TLS_ST_CW_FINISHED;
520
0
        return WRITE_TRAN_CONTINUE;
521
522
0
    case TLS_ST_CR_KEY_UPDATE:
523
0
    case TLS_ST_CW_KEY_UPDATE:
524
820
    case TLS_ST_CR_SESSION_TICKET:
525
6.63k
    case TLS_ST_CW_FINISHED:
526
6.63k
        st->hand_state = TLS_ST_OK;
527
6.63k
        return WRITE_TRAN_CONTINUE;
528
529
3.30k
    case TLS_ST_OK:
530
3.30k
        if (s->key_update != SSL_KEY_UPDATE_NONE) {
531
0
            st->hand_state = TLS_ST_CW_KEY_UPDATE;
532
0
            return WRITE_TRAN_CONTINUE;
533
0
        }
534
535
        /* Try to read from the server instead */
536
3.30k
        return WRITE_TRAN_FINISHED;
537
15.7k
    }
538
15.7k
}
539
540
/*
541
 * ossl_statem_client_write_transition() works out what handshake state to
542
 * move to next when the client is writing messages to be sent to the server.
543
 */
544
WRITE_TRAN ossl_statem_client_write_transition(SSL_CONNECTION *s)
545
150k
{
546
150k
    OSSL_STATEM *st = &s->statem;
547
548
    /*
549
     * Note that immediately before/after a ClientHello we don't know what
550
     * version we are going to negotiate yet, so we don't take this branch until
551
     * later
552
     */
553
150k
    if (SSL_CONNECTION_IS_TLS13(s))
554
15.7k
        return ossl_statem_client13_write_transition(s);
555
556
134k
    switch (st->hand_state) {
557
0
    default:
558
        /* Shouldn't happen */
559
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
560
0
        return WRITE_TRAN_ERROR;
561
562
763
    case TLS_ST_OK:
563
763
        if (!s->renegotiate) {
564
            /*
565
             * We haven't requested a renegotiation ourselves so we must have
566
             * received a message from the server. Better read it.
567
             */
568
763
            return WRITE_TRAN_FINISHED;
569
763
        }
570
        /* Renegotiation */
571
        /* fall thru */
572
52.5k
    case TLS_ST_BEFORE:
573
52.5k
        st->hand_state = TLS_ST_CW_CLNT_HELLO;
574
52.5k
        return WRITE_TRAN_CONTINUE;
575
576
54.7k
    case TLS_ST_CW_CLNT_HELLO:
577
54.7k
        if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
578
0
                && !SSL_IS_QUIC_HANDSHAKE(s)) {
579
            /*
580
             * We are assuming this is a TLSv1.3 connection, although we haven't
581
             * actually selected a version yet.
582
             */
583
0
            if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
584
0
                st->hand_state = TLS_ST_CW_CHANGE;
585
0
            else
586
0
                st->hand_state = TLS_ST_EARLY_DATA;
587
0
            return WRITE_TRAN_CONTINUE;
588
0
        }
589
        /*
590
         * No transition at the end of writing because we don't know what
591
         * we will be sent
592
         */
593
54.7k
        s->ts_msg_write = ossl_time_now();
594
54.7k
        return WRITE_TRAN_FINISHED;
595
596
183
    case TLS_ST_CR_SRVR_HELLO:
597
        /*
598
         * We only get here in TLSv1.3. We just received an HRR, so issue a
599
         * CCS unless middlebox compat mode is off, or we already issued one
600
         * because we did early data.
601
         */
602
183
        if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0
603
166
                && s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING)
604
166
            st->hand_state = TLS_ST_CW_CHANGE;
605
17
        else
606
17
            st->hand_state = TLS_ST_CW_CLNT_HELLO;
607
183
        return WRITE_TRAN_CONTINUE;
608
609
0
    case TLS_ST_EARLY_DATA:
610
0
        s->ts_msg_write = ossl_time_now();
611
0
        return WRITE_TRAN_FINISHED;
612
613
1.36k
    case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
614
1.36k
        st->hand_state = TLS_ST_CW_CLNT_HELLO;
615
1.36k
        return WRITE_TRAN_CONTINUE;
616
617
6.10k
    case TLS_ST_CR_SRVR_DONE:
618
6.10k
        s->ts_msg_read = ossl_time_now();
619
6.10k
        if (s->s3.tmp.cert_req)
620
15
            st->hand_state = TLS_ST_CW_CERT;
621
6.09k
        else
622
6.09k
            st->hand_state = TLS_ST_CW_KEY_EXCH;
623
6.10k
        return WRITE_TRAN_CONTINUE;
624
625
15
    case TLS_ST_CW_CERT:
626
15
        st->hand_state = TLS_ST_CW_KEY_EXCH;
627
15
        return WRITE_TRAN_CONTINUE;
628
629
5.66k
    case TLS_ST_CW_KEY_EXCH:
630
        /*
631
         * For TLS, cert_req is set to 2, so a cert chain of nothing is
632
         * sent, but no verify packet is sent
633
         */
634
        /*
635
         * XXX: For now, we do not support client authentication in ECDH
636
         * cipher suites with ECDH (rather than ECDSA) certificates. We
637
         * need to skip the certificate verify message when client's
638
         * ECDH public key is sent inside the client certificate.
639
         */
640
5.66k
        if (s->s3.tmp.cert_req == 1) {
641
0
            st->hand_state = TLS_ST_CW_CERT_VRFY;
642
5.66k
        } else {
643
5.66k
            st->hand_state = TLS_ST_CW_CHANGE;
644
5.66k
        }
645
5.66k
        if (s->s3.flags & TLS1_FLAGS_SKIP_CERT_VERIFY) {
646
0
            st->hand_state = TLS_ST_CW_CHANGE;
647
0
        }
648
5.66k
        return WRITE_TRAN_CONTINUE;
649
650
0
    case TLS_ST_CW_CERT_VRFY:
651
0
        st->hand_state = TLS_ST_CW_CHANGE;
652
0
        return WRITE_TRAN_CONTINUE;
653
654
5.83k
    case TLS_ST_CW_CHANGE:
655
5.83k
        if (s->hello_retry_request == SSL_HRR_PENDING) {
656
166
            st->hand_state = TLS_ST_CW_CLNT_HELLO;
657
5.66k
        } else if (s->early_data_state == SSL_EARLY_DATA_CONNECTING) {
658
0
            st->hand_state = TLS_ST_EARLY_DATA;
659
5.66k
        } else {
660
#if defined(OPENSSL_NO_NEXTPROTONEG)
661
            st->hand_state = TLS_ST_CW_FINISHED;
662
#else
663
5.66k
            if (!SSL_CONNECTION_IS_DTLS(s) && s->s3.npn_seen)
664
0
                st->hand_state = TLS_ST_CW_NEXT_PROTO;
665
5.66k
            else
666
5.66k
                st->hand_state = TLS_ST_CW_FINISHED;
667
5.66k
#endif
668
5.66k
        }
669
5.83k
        return WRITE_TRAN_CONTINUE;
670
671
0
#if !defined(OPENSSL_NO_NEXTPROTONEG)
672
0
    case TLS_ST_CW_NEXT_PROTO:
673
0
        st->hand_state = TLS_ST_CW_FINISHED;
674
0
        return WRITE_TRAN_CONTINUE;
675
0
#endif
676
677
5.66k
    case TLS_ST_CW_FINISHED:
678
5.66k
        if (s->hit) {
679
0
            st->hand_state = TLS_ST_OK;
680
0
            return WRITE_TRAN_CONTINUE;
681
5.66k
        } else {
682
5.66k
            return WRITE_TRAN_FINISHED;
683
5.66k
        }
684
685
860
    case TLS_ST_CR_FINISHED:
686
860
        if (s->hit) {
687
0
            st->hand_state = TLS_ST_CW_CHANGE;
688
0
            return WRITE_TRAN_CONTINUE;
689
860
        } else {
690
860
            st->hand_state = TLS_ST_OK;
691
860
            return WRITE_TRAN_CONTINUE;
692
860
        }
693
694
712
    case TLS_ST_CR_HELLO_REQ:
695
        /*
696
         * If we can renegotiate now then do so, otherwise wait for a more
697
         * convenient time.
698
         */
699
712
        if (ssl3_renegotiate_check(SSL_CONNECTION_GET_SSL(s), 1)) {
700
712
            if (!tls_setup_handshake(s)) {
701
                /* SSLfatal() already called */
702
0
                return WRITE_TRAN_ERROR;
703
0
            }
704
712
            st->hand_state = TLS_ST_CW_CLNT_HELLO;
705
712
            return WRITE_TRAN_CONTINUE;
706
712
        }
707
0
        st->hand_state = TLS_ST_OK;
708
0
        return WRITE_TRAN_CONTINUE;
709
134k
    }
710
134k
}
711
712
/*
713
 * Perform any pre work that needs to be done prior to sending a message from
714
 * the client to the server.
715
 */
716
WORK_STATE ossl_statem_client_pre_work(SSL_CONNECTION *s, WORK_STATE wst)
717
179k
{
718
179k
    OSSL_STATEM *st = &s->statem;
719
720
179k
    switch (st->hand_state) {
721
36.4k
    default:
722
        /* No pre work to be done */
723
36.4k
        break;
724
725
115k
    case TLS_ST_CW_CLNT_HELLO:
726
115k
        s->shutdown = 0;
727
115k
        if (SSL_CONNECTION_IS_DTLS(s)) {
728
            /* every DTLS ClientHello resets Finished MAC */
729
22.6k
            if (!ssl3_init_finished_mac(s)) {
730
                /* SSLfatal() already called */
731
0
                return WORK_ERROR;
732
0
            }
733
92.4k
        } else if (s->ext.early_data == SSL_EARLY_DATA_REJECTED) {
734
            /*
735
             * This must be a second ClientHello after an HRR following an
736
             * earlier rejected attempt to send early data. Since we were
737
             * previously encrypting the early data we now need to reset the
738
             * write record layer in order to write in plaintext again.
739
             */
740
0
            if (!ssl_set_new_record_layer(s,
741
0
                                          TLS_ANY_VERSION,
742
0
                                          OSSL_RECORD_DIRECTION_WRITE,
743
0
                                          OSSL_RECORD_PROTECTION_LEVEL_NONE,
744
0
                                          NULL, 0, NULL, 0, NULL, 0, NULL,  0,
745
0
                                          NULL, 0, NID_undef, NULL, NULL,
746
0
                                          NULL)) {
747
                /* SSLfatal already called */
748
0
                return WORK_ERROR;
749
0
            }
750
0
        }
751
115k
        break;
752
753
115k
    case TLS_ST_CW_CHANGE:
754
11.1k
        if (SSL_CONNECTION_IS_DTLS(s)) {
755
2.51k
            if (s->hit) {
756
                /*
757
                 * We're into the last flight so we don't retransmit these
758
                 * messages unless we need to.
759
                 */
760
0
                st->use_timer = 0;
761
0
            }
762
#ifndef OPENSSL_NO_SCTP
763
            if (BIO_dgram_is_sctp(SSL_get_wbio(SSL_CONNECTION_GET_SSL(s)))) {
764
                /* Calls SSLfatal() as required */
765
                return dtls_wait_for_dry(s);
766
            }
767
#endif
768
2.51k
        }
769
11.1k
        break;
770
771
0
    case TLS_ST_PENDING_EARLY_DATA_END:
772
        /*
773
         * If we've been called by SSL_do_handshake()/SSL_write(), or we did not
774
         * attempt to write early data before calling SSL_read() then we press
775
         * on with the handshake. Otherwise we pause here.
776
         */
777
0
        if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING
778
0
                || s->early_data_state == SSL_EARLY_DATA_NONE)
779
0
            return WORK_FINISHED_CONTINUE;
780
        /* Fall through */
781
782
0
    case TLS_ST_EARLY_DATA:
783
0
        return tls_finish_handshake(s, wst, 0, 1);
784
785
16.9k
    case TLS_ST_OK:
786
        /* Calls SSLfatal() as required */
787
16.9k
        return tls_finish_handshake(s, wst, 1, 1);
788
179k
    }
789
790
162k
    return WORK_FINISHED_CONTINUE;
791
179k
}
792
793
/*
794
 * Perform any work that needs to be done after sending a message from the
795
 * client to the server.
796
 */
797
WORK_STATE ossl_statem_client_post_work(SSL_CONNECTION *s, WORK_STATE wst)
798
77.7k
{
799
77.7k
    OSSL_STATEM *st = &s->statem;
800
77.7k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
801
802
77.7k
    s->init_num = 0;
803
804
77.7k
    switch (st->hand_state) {
805
15
    default:
806
        /* No post work to be done */
807
15
        break;
808
809
54.7k
    case TLS_ST_CW_CLNT_HELLO:
810
54.7k
        if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
811
0
                && s->max_early_data > 0) {
812
            /*
813
             * We haven't selected TLSv1.3 yet so we don't call the change
814
             * cipher state function associated with the SSL_METHOD. Instead
815
             * we call tls13_change_cipher_state() directly.
816
             */
817
0
            if ((s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0) {
818
0
                if (!tls13_change_cipher_state(s,
819
0
                            SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
820
                    /* SSLfatal() already called */
821
0
                    return WORK_ERROR;
822
0
                }
823
0
            }
824
            /* else we're in compat mode so we delay flushing until after CCS */
825
54.7k
        } else if (!statem_flush(s)) {
826
0
            return WORK_MORE_A;
827
0
        }
828
829
54.7k
        if (SSL_CONNECTION_IS_DTLS(s)) {
830
            /* Treat the next message as the first packet */
831
12.1k
            s->first_packet = 1;
832
12.1k
        }
833
54.7k
        break;
834
835
5.66k
    case TLS_ST_CW_KEY_EXCH:
836
5.66k
        if (tls_client_key_exchange_post_work(s) == 0) {
837
            /* SSLfatal() already called */
838
0
            return WORK_ERROR;
839
0
        }
840
5.66k
        break;
841
842
5.83k
    case TLS_ST_CW_CHANGE:
843
5.83k
        if (SSL_CONNECTION_IS_TLS13(s)
844
5.83k
            || s->hello_retry_request == SSL_HRR_PENDING)
845
166
            break;
846
5.66k
        if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
847
0
                    && s->max_early_data > 0) {
848
            /*
849
             * We haven't selected TLSv1.3 yet so we don't call the change
850
             * cipher state function associated with the SSL_METHOD. Instead
851
             * we call tls13_change_cipher_state() directly.
852
             */
853
0
            if (!tls13_change_cipher_state(s,
854
0
                        SSL3_CC_EARLY | SSL3_CHANGE_CIPHER_CLIENT_WRITE))
855
0
                return WORK_ERROR;
856
0
            break;
857
0
        }
858
5.66k
        s->session->cipher = s->s3.tmp.new_cipher;
859
#ifdef OPENSSL_NO_COMP
860
        s->session->compress_meth = 0;
861
#else
862
5.66k
        if (s->s3.tmp.new_compression == NULL)
863
5.66k
            s->session->compress_meth = 0;
864
0
        else
865
0
            s->session->compress_meth = s->s3.tmp.new_compression->id;
866
5.66k
#endif
867
5.66k
        if (!ssl->method->ssl3_enc->setup_key_block(s)) {
868
            /* SSLfatal() already called */
869
0
            return WORK_ERROR;
870
0
        }
871
872
5.66k
        if (!ssl->method->ssl3_enc->change_cipher_state(s,
873
5.66k
                                          SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
874
            /* SSLfatal() already called */
875
0
            return WORK_ERROR;
876
0
        }
877
878
#ifndef OPENSSL_NO_SCTP
879
        if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {
880
            /*
881
            * Change to new shared key of SCTP-Auth, will be ignored if
882
            * no SCTP used.
883
            */
884
            BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
885
                     0, NULL);
886
        }
887
#endif
888
5.66k
        break;
889
890
11.4k
    case TLS_ST_CW_FINISHED:
891
#ifndef OPENSSL_NO_SCTP
892
        if (wst == WORK_MORE_A && SSL_CONNECTION_IS_DTLS(s) && s->hit == 0) {
893
            /*
894
             * Change to new shared key of SCTP-Auth, will be ignored if
895
             * no SCTP used.
896
             */
897
            BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_NEXT_AUTH_KEY,
898
                     0, NULL);
899
        }
900
#endif
901
11.4k
        if (statem_flush(s) != 1)
902
0
            return WORK_MORE_B;
903
904
11.4k
        if (SSL_CONNECTION_IS_TLS13(s)) {
905
5.81k
            if (!tls13_save_handshake_digest_for_pha(s)) {
906
                /* SSLfatal() already called */
907
0
                return WORK_ERROR;
908
0
            }
909
5.81k
            if (s->post_handshake_auth != SSL_PHA_REQUESTED) {
910
5.81k
                if (!ssl->method->ssl3_enc->change_cipher_state(s,
911
5.81k
                        SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
912
                    /* SSLfatal() already called */
913
0
                    return WORK_ERROR;
914
0
                }
915
                /*
916
                 * For QUIC we deferred setting up these keys until now so
917
                 * that we can ensure write keys are always set up before read
918
                 * keys.
919
                 */
920
5.81k
                if (SSL_IS_QUIC_HANDSHAKE(s)
921
5.81k
                        && !ssl->method->ssl3_enc->change_cipher_state(s,
922
5.81k
                            SSL3_CC_APPLICATION | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
923
                    /* SSLfatal() already called */
924
6
                    return WORK_ERROR;
925
6
                }
926
5.81k
            }
927
5.81k
        }
928
11.4k
        break;
929
930
11.4k
    case TLS_ST_CW_KEY_UPDATE:
931
0
        if (statem_flush(s) != 1)
932
0
            return WORK_MORE_A;
933
0
        if (!tls13_update_key(s, 1)) {
934
            /* SSLfatal() already called */
935
0
            return WORK_ERROR;
936
0
        }
937
0
        break;
938
77.7k
    }
939
940
77.7k
    return WORK_FINISHED_CONTINUE;
941
77.7k
}
942
943
/*
944
 * Get the message construction function and message type for sending from the
945
 * client
946
 *
947
 * Valid return values are:
948
 *   1: Success
949
 *   0: Error
950
 */
951
int ossl_statem_client_construct_message(SSL_CONNECTION *s,
952
                                         confunc_f *confunc, int *mt)
953
172k
{
954
172k
    OSSL_STATEM *st = &s->statem;
955
956
172k
    switch (st->hand_state) {
957
0
    default:
958
        /* Shouldn't happen */
959
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_STATE);
960
0
        return 0;
961
962
12.3k
    case TLS_ST_CW_CHANGE:
963
12.3k
        if (SSL_CONNECTION_IS_DTLS(s))
964
2.51k
            *confunc = dtls_construct_change_cipher_spec;
965
9.81k
        else
966
9.81k
            *confunc = tls_construct_change_cipher_spec;
967
12.3k
        *mt = SSL3_MT_CHANGE_CIPHER_SPEC;
968
12.3k
        break;
969
970
121k
    case TLS_ST_CW_CLNT_HELLO:
971
121k
        *confunc = tls_construct_client_hello;
972
121k
        *mt = SSL3_MT_CLIENT_HELLO;
973
121k
        break;
974
975
0
    case TLS_ST_CW_END_OF_EARLY_DATA:
976
0
        *confunc = tls_construct_end_of_early_data;
977
0
        *mt = SSL3_MT_END_OF_EARLY_DATA;
978
0
        break;
979
980
0
    case TLS_ST_PENDING_EARLY_DATA_END:
981
0
        *confunc = NULL;
982
0
        *mt = SSL3_MT_DUMMY;
983
0
        break;
984
985
29
    case TLS_ST_CW_CERT:
986
29
        *confunc = tls_construct_client_certificate;
987
29
        *mt = SSL3_MT_CERTIFICATE;
988
29
        break;
989
990
#ifndef OPENSSL_NO_COMP_ALG
991
    case TLS_ST_CW_COMP_CERT:
992
        *confunc = tls_construct_client_compressed_certificate;
993
        *mt = SSL3_MT_COMPRESSED_CERTIFICATE;
994
        break;
995
#endif
996
997
13.5k
    case TLS_ST_CW_KEY_EXCH:
998
13.5k
        *confunc = tls_construct_client_key_exchange;
999
13.5k
        *mt = SSL3_MT_CLIENT_KEY_EXCHANGE;
1000
13.5k
        break;
1001
1002
0
    case TLS_ST_CW_CERT_VRFY:
1003
0
        *confunc = tls_construct_cert_verify;
1004
0
        *mt = SSL3_MT_CERTIFICATE_VERIFY;
1005
0
        break;
1006
1007
0
#if !defined(OPENSSL_NO_NEXTPROTONEG)
1008
0
    case TLS_ST_CW_NEXT_PROTO:
1009
0
        *confunc = tls_construct_next_proto;
1010
0
        *mt = SSL3_MT_NEXT_PROTO;
1011
0
        break;
1012
0
#endif
1013
25.3k
    case TLS_ST_CW_FINISHED:
1014
25.3k
        *confunc = tls_construct_finished;
1015
25.3k
        *mt = SSL3_MT_FINISHED;
1016
25.3k
        break;
1017
1018
0
    case TLS_ST_CW_KEY_UPDATE:
1019
0
        *confunc = tls_construct_key_update;
1020
0
        *mt = SSL3_MT_KEY_UPDATE;
1021
0
        break;
1022
172k
    }
1023
1024
172k
    return 1;
1025
172k
}
1026
1027
/*
1028
 * Returns the maximum allowed length for the current message that we are
1029
 * reading. Excludes the message header.
1030
 */
1031
size_t ossl_statem_client_max_message_size(SSL_CONNECTION *s)
1032
229k
{
1033
229k
    OSSL_STATEM *st = &s->statem;
1034
1035
229k
    switch (st->hand_state) {
1036
1.38k
    default:
1037
        /* Shouldn't happen */
1038
1.38k
        return 0;
1039
1040
75.5k
    case TLS_ST_CR_SRVR_HELLO:
1041
75.5k
        return SERVER_HELLO_MAX_LENGTH;
1042
1043
4.12k
    case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1044
4.12k
        return HELLO_VERIFY_REQUEST_MAX_LENGTH;
1045
1046
0
    case TLS_ST_CR_COMP_CERT:
1047
49.3k
    case TLS_ST_CR_CERT:
1048
49.3k
        return s->max_cert_list;
1049
1050
18.0k
    case TLS_ST_CR_CERT_VRFY:
1051
18.0k
        return CERTIFICATE_VERIFY_MAX_LENGTH;
1052
1053
0
    case TLS_ST_CR_CERT_STATUS:
1054
0
        return SSL3_RT_MAX_PLAIN_LENGTH;
1055
1056
17.2k
    case TLS_ST_CR_KEY_EXCH:
1057
17.2k
        return SERVER_KEY_EXCH_MAX_LENGTH;
1058
1059
837
    case TLS_ST_CR_CERT_REQ:
1060
        /*
1061
         * Set to s->max_cert_list for compatibility with previous releases. In
1062
         * practice these messages can get quite long if servers are configured
1063
         * to provide a long list of acceptable CAs
1064
         */
1065
837
        return s->max_cert_list;
1066
1067
12.2k
    case TLS_ST_CR_SRVR_DONE:
1068
12.2k
        return SERVER_HELLO_DONE_MAX_LENGTH;
1069
1070
4.51k
    case TLS_ST_CR_CHANGE:
1071
4.51k
        if (s->version == DTLS1_BAD_VER)
1072
0
            return 3;
1073
4.51k
        return CCS_MAX_LENGTH;
1074
1075
7.48k
    case TLS_ST_CR_SESSION_TICKET:
1076
7.48k
        return (SSL_CONNECTION_IS_TLS13(s)) ? SESSION_TICKET_MAX_LENGTH_TLS13
1077
7.48k
                                            : SESSION_TICKET_MAX_LENGTH_TLS12;
1078
1079
15.3k
    case TLS_ST_CR_FINISHED:
1080
15.3k
        return FINISHED_MAX_LENGTH;
1081
1082
23.2k
    case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
1083
23.2k
        return ENCRYPTED_EXTENSIONS_MAX_LENGTH;
1084
1085
0
    case TLS_ST_CR_KEY_UPDATE:
1086
0
        return KEY_UPDATE_MAX_LENGTH;
1087
229k
    }
1088
229k
}
1089
1090
/*
1091
 * Process a message that the client has received from the server.
1092
 */
1093
MSG_PROCESS_RETURN ossl_statem_client_process_message(SSL_CONNECTION *s,
1094
                                                      PACKET *pkt)
1095
234k
{
1096
234k
    OSSL_STATEM *st = &s->statem;
1097
1098
234k
    switch (st->hand_state) {
1099
0
    default:
1100
        /* Shouldn't happen */
1101
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1102
0
        return MSG_PROCESS_ERROR;
1103
1104
79.1k
    case TLS_ST_CR_SRVR_HELLO:
1105
79.1k
        return tls_process_server_hello(s, pkt);
1106
1107
4.02k
    case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1108
4.02k
        return dtls_process_hello_verify(s, pkt);
1109
1110
52.8k
    case TLS_ST_CR_CERT:
1111
52.8k
        return tls_process_server_certificate(s, pkt);
1112
1113
#ifndef OPENSSL_NO_COMP_ALG
1114
    case TLS_ST_CR_COMP_CERT:
1115
        return tls_process_server_compressed_certificate(s, pkt);
1116
#endif
1117
1118
17.5k
    case TLS_ST_CR_CERT_VRFY:
1119
17.5k
        return tls_process_cert_verify(s, pkt);
1120
1121
0
    case TLS_ST_CR_CERT_STATUS:
1122
0
        return tls_process_cert_status(s, pkt);
1123
1124
19.5k
    case TLS_ST_CR_KEY_EXCH:
1125
19.5k
        return tls_process_key_exchange(s, pkt);
1126
1127
931
    case TLS_ST_CR_CERT_REQ:
1128
931
        return tls_process_certificate_request(s, pkt);
1129
1130
13.5k
    case TLS_ST_CR_SRVR_DONE:
1131
13.5k
        return tls_process_server_done(s, pkt);
1132
1133
4.85k
    case TLS_ST_CR_CHANGE:
1134
4.85k
        return tls_process_change_cipher_spec(s, pkt);
1135
1136
2.38k
    case TLS_ST_CR_SESSION_TICKET:
1137
2.38k
        return tls_process_new_session_ticket(s, pkt);
1138
1139
15.2k
    case TLS_ST_CR_FINISHED:
1140
15.2k
        return tls_process_finished(s, pkt);
1141
1142
1.35k
    case TLS_ST_CR_HELLO_REQ:
1143
1.35k
        return tls_process_hello_req(s, pkt);
1144
1145
23.2k
    case TLS_ST_CR_ENCRYPTED_EXTENSIONS:
1146
23.2k
        return tls_process_encrypted_extensions(s, pkt);
1147
1148
0
    case TLS_ST_CR_KEY_UPDATE:
1149
0
        return tls_process_key_update(s, pkt);
1150
234k
    }
1151
234k
}
1152
1153
/*
1154
 * Perform any further processing required following the receipt of a message
1155
 * from the server
1156
 */
1157
WORK_STATE ossl_statem_client_post_process_message(SSL_CONNECTION *s,
1158
                                                   WORK_STATE wst)
1159
32.5k
{
1160
32.5k
    OSSL_STATEM *st = &s->statem;
1161
1162
32.5k
    switch (st->hand_state) {
1163
0
    default:
1164
        /* Shouldn't happen */
1165
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1166
0
        return WORK_ERROR;
1167
1168
32.5k
    case TLS_ST_CR_CERT:
1169
32.5k
    case TLS_ST_CR_COMP_CERT:
1170
32.5k
        return tls_post_process_server_certificate(s, wst);
1171
1172
0
    case TLS_ST_CR_CERT_VRFY:
1173
44
    case TLS_ST_CR_CERT_REQ:
1174
44
        return tls_prepare_client_certificate(s, wst);
1175
32.5k
    }
1176
32.5k
}
1177
1178
CON_FUNC_RETURN tls_construct_client_hello(SSL_CONNECTION *s, WPACKET *pkt)
1179
121k
{
1180
121k
    unsigned char *p;
1181
121k
    size_t sess_id_len;
1182
121k
    int i, protverr;
1183
121k
#ifndef OPENSSL_NO_COMP
1184
121k
    SSL_COMP *comp;
1185
121k
#endif
1186
121k
    SSL_SESSION *sess = s->session;
1187
121k
    unsigned char *session_id;
1188
121k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1189
1190
    /* Work out what SSL/TLS/DTLS version to use */
1191
121k
    protverr = ssl_set_client_hello_version(s);
1192
121k
    if (protverr != 0) {
1193
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, protverr);
1194
0
        return CON_FUNC_ERROR;
1195
0
    }
1196
1197
121k
    if (sess == NULL
1198
5.85k
            || !ssl_version_supported(s, sess->ssl_version, NULL)
1199
120k
            || !SSL_SESSION_is_resumable(sess)) {
1200
120k
        if (s->hello_retry_request == SSL_HRR_NONE
1201
120k
                && !ssl_get_new_session(s, 0)) {
1202
            /* SSLfatal() already called */
1203
0
            return CON_FUNC_ERROR;
1204
0
        }
1205
120k
    }
1206
    /* else use the pre-loaded session */
1207
1208
121k
    p = s->s3.client_random;
1209
1210
    /*
1211
     * for DTLS if client_random is initialized, reuse it, we are
1212
     * required to use same upon reply to HelloVerify
1213
     */
1214
121k
    if (SSL_CONNECTION_IS_DTLS(s)) {
1215
22.6k
        size_t idx;
1216
22.6k
        i = 1;
1217
618k
        for (idx = 0; idx < sizeof(s->s3.client_random); idx++) {
1218
599k
            if (p[idx]) {
1219
3.98k
                i = 0;
1220
3.98k
                break;
1221
3.98k
            }
1222
599k
        }
1223
98.8k
    } else {
1224
98.8k
        i = (s->hello_retry_request == SSL_HRR_NONE);
1225
98.8k
    }
1226
1227
121k
    if (i && ssl_fill_hello_random(s, 0, p, sizeof(s->s3.client_random),
1228
116k
                                   DOWNGRADE_NONE) <= 0) {
1229
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1230
0
        return CON_FUNC_ERROR;
1231
0
    }
1232
1233
    /*-
1234
     * version indicates the negotiated version: for example from
1235
     * an SSLv2/v3 compatible client hello). The client_version
1236
     * field is the maximum version we permit and it is also
1237
     * used in RSA encrypted premaster secrets. Some servers can
1238
     * choke if we initially report a higher version then
1239
     * renegotiate to a lower one in the premaster secret. This
1240
     * didn't happen with TLS 1.0 as most servers supported it
1241
     * but it can with TLS 1.1 or later if the server only supports
1242
     * 1.0.
1243
     *
1244
     * Possible scenario with previous logic:
1245
     *      1. Client hello indicates TLS 1.2
1246
     *      2. Server hello says TLS 1.0
1247
     *      3. RSA encrypted premaster secret uses 1.2.
1248
     *      4. Handshake proceeds using TLS 1.0.
1249
     *      5. Server sends hello request to renegotiate.
1250
     *      6. Client hello indicates TLS v1.0 as we now
1251
     *         know that is maximum server supports.
1252
     *      7. Server chokes on RSA encrypted premaster secret
1253
     *         containing version 1.0.
1254
     *
1255
     * For interoperability it should be OK to always use the
1256
     * maximum version we support in client hello and then rely
1257
     * on the checking of version to ensure the servers isn't
1258
     * being inconsistent: for example initially negotiating with
1259
     * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
1260
     * client_version in client hello and not resetting it to
1261
     * the negotiated version.
1262
     *
1263
     * For TLS 1.3 we always set the ClientHello version to 1.2 and rely on the
1264
     * supported_versions extension for the real supported versions.
1265
     */
1266
121k
    if (!WPACKET_put_bytes_u16(pkt, s->client_version)
1267
121k
            || !WPACKET_memcpy(pkt, s->s3.client_random, SSL3_RANDOM_SIZE)) {
1268
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1269
0
        return CON_FUNC_ERROR;
1270
0
    }
1271
1272
    /* Session ID */
1273
121k
    session_id = s->session->session_id;
1274
121k
    if (s->new_session || s->session->ssl_version == TLS1_3_VERSION) {
1275
97.4k
        if (s->version == TLS1_3_VERSION
1276
97.4k
                && (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0) {
1277
42.5k
            sess_id_len = sizeof(s->tmp_session_id);
1278
42.5k
            s->tmp_session_id_len = sess_id_len;
1279
42.5k
            session_id = s->tmp_session_id;
1280
42.5k
            if (s->hello_retry_request == SSL_HRR_NONE
1281
42.0k
                    && RAND_bytes_ex(sctx->libctx, s->tmp_session_id,
1282
42.0k
                                     sess_id_len, 0) <= 0) {
1283
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1284
0
                return CON_FUNC_ERROR;
1285
0
            }
1286
54.9k
        } else {
1287
54.9k
            sess_id_len = 0;
1288
54.9k
        }
1289
97.4k
    } else {
1290
23.9k
        assert(s->session->session_id_length <= sizeof(s->session->session_id));
1291
23.9k
        sess_id_len = s->session->session_id_length;
1292
23.9k
        if (s->version == TLS1_3_VERSION) {
1293
0
            s->tmp_session_id_len = sess_id_len;
1294
0
            memcpy(s->tmp_session_id, s->session->session_id, sess_id_len);
1295
0
        }
1296
23.9k
    }
1297
121k
    if (!WPACKET_start_sub_packet_u8(pkt)
1298
121k
            || (sess_id_len != 0 && !WPACKET_memcpy(pkt, session_id,
1299
43.4k
                                                    sess_id_len))
1300
121k
            || !WPACKET_close(pkt)) {
1301
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1302
0
        return CON_FUNC_ERROR;
1303
0
    }
1304
1305
    /* cookie stuff for DTLS */
1306
121k
    if (SSL_CONNECTION_IS_DTLS(s)) {
1307
22.6k
        if (s->d1->cookie_len > sizeof(s->d1->cookie)
1308
22.6k
                || !WPACKET_sub_memcpy_u8(pkt, s->d1->cookie,
1309
22.6k
                                          s->d1->cookie_len)) {
1310
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1311
0
            return CON_FUNC_ERROR;
1312
0
        }
1313
22.6k
    }
1314
1315
    /* Ciphers supported */
1316
121k
    if (!WPACKET_start_sub_packet_u16(pkt)) {
1317
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1318
0
        return CON_FUNC_ERROR;
1319
0
    }
1320
1321
121k
    if (!ssl_cipher_list_to_bytes(s, SSL_get_ciphers(SSL_CONNECTION_GET_SSL(s)),
1322
121k
                                  pkt)) {
1323
        /* SSLfatal() already called */
1324
0
        return CON_FUNC_ERROR;
1325
0
    }
1326
121k
    if (!WPACKET_close(pkt)) {
1327
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1328
0
        return CON_FUNC_ERROR;
1329
0
    }
1330
1331
    /* COMPRESSION */
1332
121k
    if (!WPACKET_start_sub_packet_u8(pkt)) {
1333
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1334
0
        return CON_FUNC_ERROR;
1335
0
    }
1336
121k
#ifndef OPENSSL_NO_COMP
1337
121k
    if (ssl_allow_compression(s)
1338
0
            && sctx->comp_methods
1339
0
            && (SSL_CONNECTION_IS_DTLS(s)
1340
0
                || s->s3.tmp.max_ver < TLS1_3_VERSION)) {
1341
0
        int compnum = sk_SSL_COMP_num(sctx->comp_methods);
1342
0
        for (i = 0; i < compnum; i++) {
1343
0
            comp = sk_SSL_COMP_value(sctx->comp_methods, i);
1344
0
            if (!WPACKET_put_bytes_u8(pkt, comp->id)) {
1345
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1346
0
                return CON_FUNC_ERROR;
1347
0
            }
1348
0
        }
1349
0
    }
1350
121k
#endif
1351
    /* Add the NULL method */
1352
121k
    if (!WPACKET_put_bytes_u8(pkt, 0) || !WPACKET_close(pkt)) {
1353
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1354
0
        return CON_FUNC_ERROR;
1355
0
    }
1356
1357
    /* TLS extensions */
1358
121k
    if (!tls_construct_extensions(s, pkt, SSL_EXT_CLIENT_HELLO, NULL, 0)) {
1359
        /* SSLfatal() already called */
1360
0
        return CON_FUNC_ERROR;
1361
0
    }
1362
1363
121k
    return CON_FUNC_SUCCESS;
1364
121k
}
1365
1366
MSG_PROCESS_RETURN dtls_process_hello_verify(SSL_CONNECTION *s, PACKET *pkt)
1367
4.02k
{
1368
4.02k
    size_t cookie_len;
1369
4.02k
    PACKET cookiepkt;
1370
1371
4.02k
    if (!PACKET_forward(pkt, 2)
1372
4.01k
        || !PACKET_get_length_prefixed_1(pkt, &cookiepkt)) {
1373
39
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1374
39
        return MSG_PROCESS_ERROR;
1375
39
    }
1376
1377
3.98k
    cookie_len = PACKET_remaining(&cookiepkt);
1378
3.98k
    if (cookie_len > sizeof(s->d1->cookie)) {
1379
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_LENGTH_TOO_LONG);
1380
0
        return MSG_PROCESS_ERROR;
1381
0
    }
1382
1383
3.98k
    if (!PACKET_copy_bytes(&cookiepkt, s->d1->cookie, cookie_len)) {
1384
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1385
0
        return MSG_PROCESS_ERROR;
1386
0
    }
1387
3.98k
    s->d1->cookie_len = cookie_len;
1388
1389
3.98k
    return MSG_PROCESS_FINISHED_READING;
1390
3.98k
}
1391
1392
static int set_client_ciphersuite(SSL_CONNECTION *s,
1393
                                  const unsigned char *cipherchars)
1394
58.5k
{
1395
58.5k
    STACK_OF(SSL_CIPHER) *sk;
1396
58.5k
    const SSL_CIPHER *c;
1397
58.5k
    int i;
1398
58.5k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
1399
1400
58.5k
    c = ssl_get_cipher_by_char(s, cipherchars, 0);
1401
58.5k
    if (c == NULL) {
1402
        /* unknown cipher */
1403
257
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CIPHER_RETURNED);
1404
257
        return 0;
1405
257
    }
1406
    /*
1407
     * If it is a disabled cipher we either didn't send it in client hello,
1408
     * or it's not allowed for the selected protocol. So we return an error.
1409
     */
1410
58.2k
    if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_CHECK, 1)) {
1411
111
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);
1412
111
        return 0;
1413
111
    }
1414
1415
58.1k
    sk = ssl_get_ciphers_by_id(s);
1416
58.1k
    i = sk_SSL_CIPHER_find(sk, c);
1417
58.1k
    if (i < 0) {
1418
        /* we did not say we would use this cipher */
1419
36
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);
1420
36
        return 0;
1421
36
    }
1422
1423
58.1k
    if (SSL_CONNECTION_IS_TLS13(s) && s->s3.tmp.new_cipher != NULL
1424
69
            && s->s3.tmp.new_cipher->id != c->id) {
1425
        /* ServerHello selected a different ciphersuite to that in the HRR */
1426
6
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CIPHER_RETURNED);
1427
6
        return 0;
1428
6
    }
1429
1430
    /*
1431
     * Depending on the session caching (internal/external), the cipher
1432
     * and/or cipher_id values may not be set. Make sure that cipher_id is
1433
     * set and use it for comparison.
1434
     */
1435
58.1k
    if (s->session->cipher != NULL)
1436
24
        s->session->cipher_id = s->session->cipher->id;
1437
58.1k
    if (s->hit && (s->session->cipher_id != c->id)) {
1438
5
        if (SSL_CONNECTION_IS_TLS13(s)) {
1439
0
            const EVP_MD *md = ssl_md(sctx, c->algorithm2);
1440
1441
0
            if (!ossl_assert(s->session->cipher != NULL)) {
1442
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1443
0
                return 0;
1444
0
            }
1445
            /*
1446
             * In TLSv1.3 it is valid for the server to select a different
1447
             * ciphersuite as long as the hash is the same.
1448
             */
1449
0
            if (md == NULL
1450
0
                    || md != ssl_md(sctx, s->session->cipher->algorithm2)) {
1451
0
                SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1452
0
                         SSL_R_CIPHERSUITE_DIGEST_HAS_CHANGED);
1453
0
                return 0;
1454
0
            }
1455
5
        } else {
1456
            /*
1457
             * Prior to TLSv1.3 resuming a session always meant using the same
1458
             * ciphersuite.
1459
             */
1460
5
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1461
5
                     SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
1462
5
            return 0;
1463
5
        }
1464
5
    }
1465
58.1k
    s->s3.tmp.new_cipher = c;
1466
1467
58.1k
    return 1;
1468
58.1k
}
1469
1470
MSG_PROCESS_RETURN tls_process_server_hello(SSL_CONNECTION *s, PACKET *pkt)
1471
35.3k
{
1472
35.3k
    PACKET session_id, extpkt;
1473
35.3k
    size_t session_id_len;
1474
35.3k
    const unsigned char *cipherchars;
1475
35.3k
    int hrr = 0;
1476
35.3k
    unsigned int compression;
1477
35.3k
    unsigned int sversion;
1478
35.3k
    unsigned int context;
1479
35.3k
    RAW_EXTENSION *extensions = NULL;
1480
35.3k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1481
35.3k
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
1482
35.3k
#ifndef OPENSSL_NO_COMP
1483
35.3k
    SSL_COMP *comp;
1484
35.3k
#endif
1485
1486
35.3k
    if (!PACKET_get_net_2(pkt, &sversion)) {
1487
45
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1488
45
        goto err;
1489
45
    }
1490
1491
    /* load the server random */
1492
35.2k
    if (s->version == TLS1_3_VERSION
1493
28.2k
            && sversion == TLS1_2_VERSION
1494
22.1k
            && PACKET_remaining(pkt) >= SSL3_RANDOM_SIZE
1495
22.1k
            && memcmp(hrrrandom, PACKET_data(pkt), SSL3_RANDOM_SIZE) == 0) {
1496
420
        if (s->hello_retry_request != SSL_HRR_NONE) {
1497
4
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1498
4
            goto err;
1499
4
        }
1500
416
        s->hello_retry_request = SSL_HRR_PENDING;
1501
        /* Tell the record layer that we know we're going to get TLSv1.3 */
1502
416
        if (!ssl_set_record_protocol_version(s, s->version)) {
1503
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1504
0
            goto err;
1505
0
        }
1506
416
        hrr = 1;
1507
416
        if (!PACKET_forward(pkt, SSL3_RANDOM_SIZE)) {
1508
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1509
0
            goto err;
1510
0
        }
1511
34.8k
    } else {
1512
34.8k
        if (!PACKET_copy_bytes(pkt, s->s3.server_random, SSL3_RANDOM_SIZE)) {
1513
76
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1514
76
            goto err;
1515
76
        }
1516
34.8k
    }
1517
1518
    /* Get the session-id. */
1519
35.2k
    if (!PACKET_get_length_prefixed_1(pkt, &session_id)) {
1520
226
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1521
226
        goto err;
1522
226
    }
1523
34.9k
    session_id_len = PACKET_remaining(&session_id);
1524
34.9k
    if (session_id_len > sizeof(s->session->session_id)
1525
34.9k
        || session_id_len > SSL3_SESSION_ID_SIZE) {
1526
25
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_SSL3_SESSION_ID_TOO_LONG);
1527
25
        goto err;
1528
25
    }
1529
1530
34.9k
    if (!PACKET_get_bytes(pkt, &cipherchars, TLS_CIPHER_LEN)) {
1531
15
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1532
15
        goto err;
1533
15
    }
1534
1535
34.9k
    if (!PACKET_get_1(pkt, &compression)) {
1536
11
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
1537
11
        goto err;
1538
11
    }
1539
1540
    /* TLS extensions */
1541
34.9k
    if (PACKET_remaining(pkt) == 0 && !hrr) {
1542
341
        PACKET_null_init(&extpkt);
1543
34.5k
    } else if (!PACKET_as_length_prefixed_2(pkt, &extpkt)
1544
34.2k
               || PACKET_remaining(pkt) != 0) {
1545
372
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
1546
372
        goto err;
1547
372
    }
1548
1549
34.5k
    if (!hrr) {
1550
34.1k
        if (!tls_collect_extensions(s, &extpkt,
1551
34.1k
                                    SSL_EXT_TLS1_2_SERVER_HELLO
1552
34.1k
                                    | SSL_EXT_TLS1_3_SERVER_HELLO,
1553
34.1k
                                    &extensions, NULL, 1)) {
1554
            /* SSLfatal() already called */
1555
306
            goto err;
1556
306
        }
1557
1558
33.8k
        if (!ssl_choose_client_version(s, sversion, extensions)) {
1559
            /* SSLfatal() already called */
1560
456
            goto err;
1561
456
        }
1562
33.8k
    }
1563
1564
33.8k
    if (SSL_CONNECTION_IS_TLS13(s) || hrr) {
1565
12.7k
        if (compression != 0) {
1566
11
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1567
11
                     SSL_R_INVALID_COMPRESSION_ALGORITHM);
1568
11
            goto err;
1569
11
        }
1570
1571
12.7k
        if (session_id_len != s->tmp_session_id_len
1572
12.7k
                || memcmp(PACKET_data(&session_id), s->tmp_session_id,
1573
12.7k
                          session_id_len) != 0) {
1574
52
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_INVALID_SESSION_ID);
1575
52
            goto err;
1576
52
        }
1577
12.7k
    }
1578
1579
33.7k
    if (hrr) {
1580
378
        if (!set_client_ciphersuite(s, cipherchars)) {
1581
            /* SSLfatal() already called */
1582
20
            goto err;
1583
20
        }
1584
1585
358
        return tls_process_as_hello_retry_request(s, &extpkt);
1586
378
    }
1587
1588
    /*
1589
     * Now we have chosen the version we need to check again that the extensions
1590
     * are appropriate for this version.
1591
     */
1592
33.3k
    context = SSL_CONNECTION_IS_TLS13(s) ? SSL_EXT_TLS1_3_SERVER_HELLO
1593
33.3k
                                         : SSL_EXT_TLS1_2_SERVER_HELLO;
1594
33.3k
    if (!tls_validate_all_contexts(s, context, extensions)) {
1595
22
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_EXTENSION);
1596
22
        goto err;
1597
22
    }
1598
1599
33.3k
    s->hit = 0;
1600
1601
33.3k
    if (SSL_CONNECTION_IS_TLS13(s)) {
1602
        /*
1603
         * In TLSv1.3 a ServerHello message signals a key change so the end of
1604
         * the message must be on a record boundary.
1605
         */
1606
12.2k
        if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
1607
6
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1608
6
                     SSL_R_NOT_ON_RECORD_BOUNDARY);
1609
6
            goto err;
1610
6
        }
1611
1612
        /* This will set s->hit if we are resuming */
1613
12.2k
        if (!tls_parse_extension(s, TLSEXT_IDX_psk,
1614
12.2k
                                 SSL_EXT_TLS1_3_SERVER_HELLO,
1615
12.2k
                                 extensions, NULL, 0)) {
1616
            /* SSLfatal() already called */
1617
0
            goto err;
1618
0
        }
1619
21.0k
    } else {
1620
        /*
1621
         * Check if we can resume the session based on external pre-shared
1622
         * secret. EAP-FAST (RFC 4851) supports two types of session resumption.
1623
         * Resumption based on server-side state works with session IDs.
1624
         * Resumption based on pre-shared Protected Access Credentials (PACs)
1625
         * works by overriding the SessionTicket extension at the application
1626
         * layer, and does not send a session ID. (We do not know whether
1627
         * EAP-FAST servers would honour the session ID.) Therefore, the session
1628
         * ID alone is not a reliable indicator of session resumption, so we
1629
         * first check if we can resume, and later peek at the next handshake
1630
         * message to see if the server wants to resume.
1631
         */
1632
21.0k
        if (s->version >= TLS1_VERSION
1633
20.5k
                && s->ext.session_secret_cb != NULL && s->session->ext.tick) {
1634
0
            const SSL_CIPHER *pref_cipher = NULL;
1635
            /*
1636
             * s->session->master_key_length is a size_t, but this is an int for
1637
             * backwards compat reasons
1638
             */
1639
0
            int master_key_length;
1640
1641
0
            master_key_length = sizeof(s->session->master_key);
1642
0
            if (s->ext.session_secret_cb(ussl, s->session->master_key,
1643
0
                                         &master_key_length,
1644
0
                                         NULL, &pref_cipher,
1645
0
                                         s->ext.session_secret_cb_arg)
1646
0
                     && master_key_length > 0) {
1647
0
                s->session->master_key_length = master_key_length;
1648
0
                s->session->cipher = pref_cipher ?
1649
0
                    pref_cipher : ssl_get_cipher_by_char(s, cipherchars, 0);
1650
0
            } else {
1651
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1652
0
                goto err;
1653
0
            }
1654
0
        }
1655
1656
21.0k
        if (session_id_len != 0
1657
8.84k
                && session_id_len == s->session->session_id_length
1658
34
                && memcmp(PACKET_data(&session_id), s->session->session_id,
1659
34
                          session_id_len) == 0)
1660
14
            s->hit = 1;
1661
21.0k
    }
1662
1663
33.3k
    if (s->hit) {
1664
14
        if (s->sid_ctx_length != s->session->sid_ctx_length
1665
14
                || memcmp(s->session->sid_ctx, s->sid_ctx, s->sid_ctx_length)) {
1666
            /* actually a client application bug */
1667
0
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1668
0
                     SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
1669
0
            goto err;
1670
0
        }
1671
33.3k
    } else {
1672
        /*
1673
         * If we were trying for session-id reuse but the server
1674
         * didn't resume, make a new SSL_SESSION.
1675
         * In the case of EAP-FAST and PAC, we do not send a session ID,
1676
         * so the PAC-based session secret is always preserved. It'll be
1677
         * overwritten if the server refuses resumption.
1678
         */
1679
33.3k
        if (s->session->session_id_length > 0) {
1680
24
            ssl_tsan_counter(s->session_ctx, &s->session_ctx->stats.sess_miss);
1681
24
            if (!ssl_get_new_session(s, 0)) {
1682
                /* SSLfatal() already called */
1683
0
                goto err;
1684
0
            }
1685
24
        }
1686
1687
33.3k
        s->session->ssl_version = s->version;
1688
        /*
1689
         * In TLSv1.2 and below we save the session id we were sent so we can
1690
         * resume it later. In TLSv1.3 the session id we were sent is just an
1691
         * echo of what we originally sent in the ClientHello and should not be
1692
         * used for resumption.
1693
         */
1694
33.3k
        if (!SSL_CONNECTION_IS_TLS13(s)) {
1695
21.0k
            s->session->session_id_length = session_id_len;
1696
            /* session_id_len could be 0 */
1697
21.0k
            if (session_id_len > 0)
1698
8.82k
                memcpy(s->session->session_id, PACKET_data(&session_id),
1699
8.82k
                       session_id_len);
1700
21.0k
        }
1701
33.3k
    }
1702
1703
    /* Session version and negotiated protocol version should match */
1704
33.3k
    if (s->version != s->session->ssl_version) {
1705
0
        SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
1706
0
                 SSL_R_SSL_SESSION_VERSION_MISMATCH);
1707
0
        goto err;
1708
0
    }
1709
    /*
1710
     * Now that we know the version, update the check to see if it's an allowed
1711
     * version.
1712
     */
1713
33.3k
    s->s3.tmp.min_ver = s->version;
1714
33.3k
    s->s3.tmp.max_ver = s->version;
1715
1716
33.3k
    if (!set_client_ciphersuite(s, cipherchars)) {
1717
        /* SSLfatal() already called */
1718
210
        goto err;
1719
210
    }
1720
1721
#ifdef OPENSSL_NO_COMP
1722
    if (compression != 0) {
1723
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1724
                 SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1725
        goto err;
1726
    }
1727
    /*
1728
     * If compression is disabled we'd better not try to resume a session
1729
     * using compression.
1730
     */
1731
    if (s->session->compress_meth != 0) {
1732
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_INCONSISTENT_COMPRESSION);
1733
        goto err;
1734
    }
1735
#else
1736
33.1k
    if (s->hit && compression != s->session->compress_meth) {
1737
4
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1738
4
                 SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1739
4
        goto err;
1740
4
    }
1741
33.1k
    if (compression == 0)
1742
33.0k
        comp = NULL;
1743
40
    else if (!ssl_allow_compression(s)) {
1744
40
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_COMPRESSION_DISABLED);
1745
40
        goto err;
1746
40
    } else {
1747
0
        comp = ssl3_comp_find(SSL_CONNECTION_GET_CTX(s)->comp_methods,
1748
0
                              compression);
1749
0
    }
1750
1751
33.0k
    if (compression != 0 && comp == NULL) {
1752
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER,
1753
0
                 SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1754
0
        goto err;
1755
33.0k
    } else {
1756
33.0k
        s->s3.tmp.new_compression = comp;
1757
33.0k
    }
1758
33.0k
#endif
1759
1760
33.0k
    if (!tls_parse_all_extensions(s, context, extensions, NULL, 0, 1)) {
1761
        /* SSLfatal() already called */
1762
420
        goto err;
1763
420
    }
1764
1765
#ifndef OPENSSL_NO_SCTP
1766
    if (SSL_CONNECTION_IS_DTLS(s) && s->hit) {
1767
        unsigned char sctpauthkey[64];
1768
        char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
1769
        size_t labellen;
1770
1771
        /*
1772
         * Add new shared key for SCTP-Auth, will be ignored if
1773
         * no SCTP used.
1774
         */
1775
        memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
1776
               sizeof(DTLS1_SCTP_AUTH_LABEL));
1777
1778
        /* Don't include the terminating zero. */
1779
        labellen = sizeof(labelbuffer) - 1;
1780
        if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
1781
            labellen += 1;
1782
1783
        if (SSL_export_keying_material(ssl, sctpauthkey,
1784
                                       sizeof(sctpauthkey),
1785
                                       labelbuffer,
1786
                                       labellen, NULL, 0, 0) <= 0) {
1787
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1788
            goto err;
1789
        }
1790
1791
        BIO_ctrl(SSL_get_wbio(ssl),
1792
                 BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
1793
                 sizeof(sctpauthkey), sctpauthkey);
1794
    }
1795
#endif
1796
1797
    /*
1798
     * In TLSv1.3 we have some post-processing to change cipher state, otherwise
1799
     * we're done with this message
1800
     */
1801
32.6k
    if (SSL_CONNECTION_IS_TLS13(s)) {
1802
11.9k
        if (!ssl->method->ssl3_enc->setup_key_block(s)
1803
11.9k
                || !tls13_store_handshake_traffic_hash(s)) {
1804
            /* SSLfatal() already called */
1805
0
            goto err;
1806
0
        }
1807
        /*
1808
         * If we're not doing early-data and we're not going to send a dummy CCS
1809
         * (i.e. no middlebox compat mode) then we can change the write keys
1810
         * immediately. Otherwise we have to defer this until after all possible
1811
         * early data is written. We could just always defer until the last
1812
         * moment except QUIC needs it done at the same time as the read keys
1813
         * are changed. Since QUIC doesn't do TLS early data or need middlebox
1814
         * compat this doesn't cause a problem.
1815
         */
1816
11.9k
        if (SSL_IS_QUIC_HANDSHAKE(s)
1817
225
                || (s->early_data_state == SSL_EARLY_DATA_NONE
1818
11.7k
                    && (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) == 0)) {
1819
11.7k
            if (!ssl->method->ssl3_enc->change_cipher_state(s,
1820
11.7k
                    SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE)) {
1821
                /* SSLfatal() already called */
1822
0
                goto err;
1823
0
                    }
1824
11.7k
        }
1825
11.9k
        if (!ssl->method->ssl3_enc->change_cipher_state(s,
1826
11.9k
                    SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_READ)) {
1827
            /* SSLfatal() already called */
1828
13
            goto err;
1829
13
        }
1830
11.9k
    }
1831
1832
32.6k
    OPENSSL_free(extensions);
1833
32.6k
    return MSG_PROCESS_CONTINUE_READING;
1834
2.33k
 err:
1835
2.33k
    OPENSSL_free(extensions);
1836
2.33k
    return MSG_PROCESS_ERROR;
1837
32.6k
}
1838
1839
static MSG_PROCESS_RETURN tls_process_as_hello_retry_request(SSL_CONNECTION *s,
1840
                                                             PACKET *extpkt)
1841
825
{
1842
825
    RAW_EXTENSION *extensions = NULL;
1843
1844
    /*
1845
     * If we were sending early_data then any alerts should not be sent using
1846
     * the old wrlmethod.
1847
     */
1848
825
    if (s->early_data_state == SSL_EARLY_DATA_FINISHED_WRITING
1849
0
            && !ssl_set_new_record_layer(s,
1850
0
                                         TLS_ANY_VERSION,
1851
0
                                         OSSL_RECORD_DIRECTION_WRITE,
1852
0
                                         OSSL_RECORD_PROTECTION_LEVEL_NONE,
1853
0
                                         NULL, 0, NULL, 0, NULL, 0, NULL,  0,
1854
0
                                         NULL, 0, NID_undef, NULL, NULL, NULL)) {
1855
        /* SSLfatal already called */
1856
0
        goto err;
1857
0
    }
1858
    /* We are definitely going to be using TLSv1.3 */
1859
825
    s->rlayer.wrlmethod->set_protocol_version(s->rlayer.wrl, TLS1_3_VERSION);
1860
1861
825
    if (!tls_collect_extensions(s, extpkt, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
1862
825
                                &extensions, NULL, 1)
1863
777
            || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_HELLO_RETRY_REQUEST,
1864
777
                                         extensions, NULL, 0, 1)) {
1865
        /* SSLfatal() already called */
1866
359
        goto err;
1867
359
    }
1868
1869
466
    OPENSSL_free(extensions);
1870
466
    extensions = NULL;
1871
1872
466
    if (s->ext.tls13_cookie_len == 0 && s->s3.tmp.pkey != NULL) {
1873
        /*
1874
         * We didn't receive a cookie or a new key_share so the next
1875
         * ClientHello will not change
1876
         */
1877
19
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_NO_CHANGE_FOLLOWING_HRR);
1878
19
        goto err;
1879
19
    }
1880
1881
    /*
1882
     * Re-initialise the Transcript Hash. We're going to prepopulate it with
1883
     * a synthetic message_hash in place of ClientHello1.
1884
     */
1885
447
    if (!create_synthetic_message_hash(s, NULL, 0, NULL, 0)) {
1886
        /* SSLfatal() already called */
1887
0
        goto err;
1888
0
    }
1889
1890
    /*
1891
     * Add this message to the Transcript Hash. Normally this is done
1892
     * automatically prior to the message processing stage. However due to the
1893
     * need to create the synthetic message hash, we defer that step until now
1894
     * for HRR messages.
1895
     */
1896
447
    if (!ssl3_finish_mac(s, (unsigned char *)s->init_buf->data,
1897
447
                                s->init_num + SSL3_HM_HEADER_LENGTH)) {
1898
        /* SSLfatal() already called */
1899
0
        goto err;
1900
0
    }
1901
1902
447
    return MSG_PROCESS_FINISHED_READING;
1903
378
 err:
1904
378
    OPENSSL_free(extensions);
1905
378
    return MSG_PROCESS_ERROR;
1906
447
}
1907
1908
MSG_PROCESS_RETURN tls_process_server_rpk(SSL_CONNECTION *sc, PACKET *pkt)
1909
0
{
1910
0
    EVP_PKEY *peer_rpk = NULL;
1911
1912
0
    if (!tls_process_rpk(sc, pkt, &peer_rpk)) {
1913
        /* SSLfatal() already called */
1914
0
        return MSG_PROCESS_ERROR;
1915
0
    }
1916
1917
0
    if (peer_rpk == NULL) {
1918
0
        SSLfatal(sc, SSL_AD_DECODE_ERROR, SSL_R_BAD_CERTIFICATE);
1919
0
        return MSG_PROCESS_ERROR;
1920
0
    }
1921
1922
0
    EVP_PKEY_free(sc->session->peer_rpk);
1923
0
    sc->session->peer_rpk = peer_rpk;
1924
1925
0
    return MSG_PROCESS_CONTINUE_PROCESSING;
1926
0
}
1927
1928
static WORK_STATE tls_post_process_server_rpk(SSL_CONNECTION *sc,
1929
                                              WORK_STATE wst)
1930
0
{
1931
0
    size_t certidx;
1932
0
    const SSL_CERT_LOOKUP *clu;
1933
0
    int v_ok;
1934
1935
0
    if (sc->session->peer_rpk == NULL) {
1936
0
        SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER,
1937
0
                 SSL_R_INVALID_RAW_PUBLIC_KEY);
1938
0
        return WORK_ERROR;
1939
0
    }
1940
1941
0
    if (sc->rwstate == SSL_RETRY_VERIFY)
1942
0
        sc->rwstate = SSL_NOTHING;
1943
1944
0
    ERR_set_mark();
1945
0
    v_ok = ssl_verify_rpk(sc, sc->session->peer_rpk);
1946
0
    if (v_ok <= 0 && sc->verify_mode != SSL_VERIFY_NONE) {
1947
0
        ERR_clear_last_mark();
1948
0
        SSLfatal(sc, ssl_x509err2alert(sc->verify_result),
1949
0
                 SSL_R_CERTIFICATE_VERIFY_FAILED);
1950
0
        return WORK_ERROR;
1951
0
    }
1952
0
    ERR_pop_to_mark();      /* but we keep s->verify_result */
1953
0
    if (v_ok > 0 && sc->rwstate == SSL_RETRY_VERIFY) {
1954
0
        return WORK_MORE_A;
1955
0
    }
1956
1957
0
    if ((clu = ssl_cert_lookup_by_pkey(sc->session->peer_rpk, &certidx,
1958
0
                                       SSL_CONNECTION_GET_CTX(sc))) == NULL) {
1959
0
        SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1960
0
        return WORK_ERROR;
1961
0
    }
1962
1963
    /*
1964
     * Check certificate type is consistent with ciphersuite. For TLS 1.3
1965
     * skip check since TLS 1.3 ciphersuites can be used with any certificate
1966
     * type.
1967
     */
1968
0
    if (!SSL_CONNECTION_IS_TLS13(sc)) {
1969
0
        if ((clu->amask & sc->s3.tmp.new_cipher->algorithm_auth) == 0) {
1970
0
            SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_RPK_TYPE);
1971
0
            return WORK_ERROR;
1972
0
        }
1973
0
    }
1974
1975
    /* Ensure there is no peer/peer_chain */
1976
0
    X509_free(sc->session->peer);
1977
0
    sc->session->peer = NULL;
1978
0
    sk_X509_pop_free(sc->session->peer_chain, X509_free);
1979
0
    sc->session->peer_chain = NULL;
1980
0
    sc->session->verify_result = sc->verify_result;
1981
1982
    /* Save the current hash state for when we receive the CertificateVerify */
1983
0
    if (SSL_CONNECTION_IS_TLS13(sc)
1984
0
            && !ssl_handshake_hash(sc, sc->cert_verify_hash,
1985
0
                                   sizeof(sc->cert_verify_hash),
1986
0
                                   &sc->cert_verify_hash_len)) {
1987
        /* SSLfatal() already called */
1988
0
        return WORK_ERROR;
1989
0
    }
1990
1991
0
    return WORK_FINISHED_CONTINUE;
1992
0
}
1993
1994
/* prepare server cert verification by setting s->session->peer_chain from pkt */
1995
MSG_PROCESS_RETURN tls_process_server_certificate(SSL_CONNECTION *s,
1996
                                                  PACKET *pkt)
1997
49.2k
{
1998
49.2k
    unsigned long cert_list_len, cert_len;
1999
49.2k
    X509 *x = NULL;
2000
49.2k
    const unsigned char *certstart, *certbytes;
2001
49.2k
    size_t chainidx;
2002
49.2k
    unsigned int context = 0;
2003
49.2k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2004
2005
49.2k
    if (s->ext.server_cert_type == TLSEXT_cert_type_rpk)
2006
0
        return tls_process_server_rpk(s, pkt);
2007
49.2k
    if (s->ext.server_cert_type != TLSEXT_cert_type_x509) {
2008
0
        SSLfatal(s, SSL_AD_UNSUPPORTED_CERTIFICATE,
2009
0
                 SSL_R_UNKNOWN_CERTIFICATE_TYPE);
2010
0
        goto err;
2011
0
    }
2012
2013
49.2k
    if ((s->session->peer_chain = sk_X509_new_null()) == NULL) {
2014
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2015
0
        goto err;
2016
0
    }
2017
2018
49.2k
    if ((SSL_CONNECTION_IS_TLS13(s) && !PACKET_get_1(pkt, &context))
2019
49.2k
            || context != 0
2020
49.2k
            || !PACKET_get_net_3(pkt, &cert_list_len)
2021
49.2k
            || PACKET_remaining(pkt) != cert_list_len
2022
48.8k
            || PACKET_remaining(pkt) == 0) {
2023
439
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2024
439
        goto err;
2025
439
    }
2026
90.1k
    for (chainidx = 0; PACKET_remaining(pkt); chainidx++) {
2027
57.5k
        if (!PACKET_get_net_3(pkt, &cert_len)
2028
57.5k
            || !PACKET_get_bytes(pkt, &certbytes, cert_len)) {
2029
231
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
2030
231
            goto err;
2031
231
        }
2032
2033
57.3k
        certstart = certbytes;
2034
57.3k
        x = X509_new_ex(sctx->libctx, sctx->propq);
2035
57.3k
        if (x == NULL) {
2036
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_ASN1_LIB);
2037
0
            goto err;
2038
0
        }
2039
57.3k
        if (d2i_X509(&x, (const unsigned char **)&certbytes,
2040
57.3k
                     cert_len) == NULL) {
2041
15.9k
            SSLfatal(s, SSL_AD_BAD_CERTIFICATE, ERR_R_ASN1_LIB);
2042
15.9k
            goto err;
2043
15.9k
        }
2044
2045
41.3k
        if (certbytes != (certstart + cert_len)) {
2046
32
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_CERT_LENGTH_MISMATCH);
2047
32
            goto err;
2048
32
        }
2049
2050
41.3k
        if (SSL_CONNECTION_IS_TLS13(s)) {
2051
18.5k
            RAW_EXTENSION *rawexts = NULL;
2052
18.5k
            PACKET extensions;
2053
2054
18.5k
            if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {
2055
76
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
2056
76
                goto err;
2057
76
            }
2058
18.5k
            if (!tls_collect_extensions(s, &extensions,
2059
18.5k
                                        SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
2060
18.5k
                                        NULL, chainidx == 0)
2061
18.5k
                || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
2062
18.5k
                                             rawexts, x, chainidx,
2063
18.5k
                                             PACKET_remaining(pkt) == 0)) {
2064
6
                OPENSSL_free(rawexts);
2065
                /* SSLfatal already called */
2066
6
                goto err;
2067
6
            }
2068
18.5k
            OPENSSL_free(rawexts);
2069
18.5k
        }
2070
2071
41.2k
        if (!sk_X509_push(s->session->peer_chain, x)) {
2072
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2073
0
            goto err;
2074
0
        }
2075
41.2k
        x = NULL;
2076
41.2k
    }
2077
32.5k
    return MSG_PROCESS_CONTINUE_PROCESSING;
2078
2079
16.7k
 err:
2080
16.7k
    X509_free(x);
2081
16.7k
    OSSL_STACK_OF_X509_free(s->session->peer_chain);
2082
16.7k
    s->session->peer_chain = NULL;
2083
16.7k
    return MSG_PROCESS_ERROR;
2084
48.8k
}
2085
2086
/*
2087
 * Verify the s->session->peer_chain and check server cert type.
2088
 * On success set s->session->peer and s->session->verify_result.
2089
 * Else the peer certificate verification callback may request retry.
2090
 */
2091
WORK_STATE tls_post_process_server_certificate(SSL_CONNECTION *s,
2092
                                               WORK_STATE wst)
2093
16.4k
{
2094
16.4k
    X509 *x;
2095
16.4k
    EVP_PKEY *pkey = NULL;
2096
16.4k
    const SSL_CERT_LOOKUP *clu;
2097
16.4k
    size_t certidx;
2098
16.4k
    int i;
2099
2100
16.4k
    if (s->ext.server_cert_type == TLSEXT_cert_type_rpk)
2101
0
        return tls_post_process_server_rpk(s, wst);
2102
2103
16.4k
    if (s->rwstate == SSL_RETRY_VERIFY)
2104
0
        s->rwstate = SSL_NOTHING;
2105
2106
    /*
2107
     * The documented interface is that SSL_VERIFY_PEER should be set in order
2108
     * for client side verification of the server certificate to take place.
2109
     * However, historically the code has only checked that *any* flag is set
2110
     * to cause server verification to take place. Use of the other flags makes
2111
     * no sense in client mode. An attempt to clean up the semantics was
2112
     * reverted because at least one application *only* set
2113
     * SSL_VERIFY_FAIL_IF_NO_PEER_CERT. Prior to the clean up this still caused
2114
     * server verification to take place, after the clean up it silently did
2115
     * nothing. SSL_CTX_set_verify()/SSL_set_verify() cannot validate the flags
2116
     * sent to them because they are void functions. Therefore, we now use the
2117
     * (less clean) historic behaviour of performing validation if any flag is
2118
     * set. The *documented* interface remains the same.
2119
     */
2120
16.4k
    ERR_set_mark();
2121
16.4k
    i = ssl_verify_cert_chain(s, s->session->peer_chain);
2122
16.4k
    if (i <= 0 && s->verify_mode != SSL_VERIFY_NONE) {
2123
0
        ERR_clear_last_mark();
2124
0
        SSLfatal(s, ssl_x509err2alert(s->verify_result),
2125
0
                 SSL_R_CERTIFICATE_VERIFY_FAILED);
2126
0
        return WORK_ERROR;
2127
0
    }
2128
16.4k
    ERR_pop_to_mark();      /* but we keep s->verify_result */
2129
16.4k
    if (i > 0 && s->rwstate == SSL_RETRY_VERIFY)
2130
0
        return WORK_MORE_A;
2131
2132
    /*
2133
     * Inconsistency alert: cert_chain does include the peer's certificate,
2134
     * which we don't include in statem_srvr.c
2135
     */
2136
16.4k
    x = sk_X509_value(s->session->peer_chain, 0);
2137
2138
16.4k
    pkey = X509_get0_pubkey(x);
2139
2140
16.4k
    if (pkey == NULL || EVP_PKEY_missing_parameters(pkey)) {
2141
773
        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2142
773
                 SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
2143
773
        return WORK_ERROR;
2144
773
    }
2145
2146
15.6k
    if ((clu = ssl_cert_lookup_by_pkey(pkey, &certidx,
2147
15.6k
               SSL_CONNECTION_GET_CTX(s))) == NULL) {
2148
21
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_CERTIFICATE_TYPE);
2149
21
        return WORK_ERROR;
2150
21
    }
2151
    /*
2152
     * Check certificate type is consistent with ciphersuite. For TLS 1.3
2153
     * skip check since TLS 1.3 ciphersuites can be used with any certificate
2154
     * type.
2155
     */
2156
15.6k
    if (!SSL_CONNECTION_IS_TLS13(s)) {
2157
7.47k
        if ((clu->amask & s->s3.tmp.new_cipher->algorithm_auth) == 0) {
2158
100
            SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CERTIFICATE_TYPE);
2159
100
            return WORK_ERROR;
2160
100
        }
2161
7.47k
    }
2162
2163
15.5k
    if (!X509_up_ref(x)) {
2164
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2165
0
        return WORK_ERROR;
2166
0
    }
2167
2168
15.5k
    X509_free(s->session->peer);
2169
15.5k
    s->session->peer = x;
2170
15.5k
    s->session->verify_result = s->verify_result;
2171
    /* Ensure there is no RPK */
2172
15.5k
    EVP_PKEY_free(s->session->peer_rpk);
2173
15.5k
    s->session->peer_rpk = NULL;
2174
2175
    /* Save the current hash state for when we receive the CertificateVerify */
2176
15.5k
    if (SSL_CONNECTION_IS_TLS13(s)
2177
8.13k
            && !ssl_handshake_hash(s, s->cert_verify_hash,
2178
8.13k
                                   sizeof(s->cert_verify_hash),
2179
8.13k
                                   &s->cert_verify_hash_len)) {
2180
0
        /* SSLfatal() already called */;
2181
0
        return WORK_ERROR;
2182
0
    }
2183
15.5k
    return WORK_FINISHED_CONTINUE;
2184
15.5k
}
2185
2186
#ifndef OPENSSL_NO_COMP_ALG
2187
MSG_PROCESS_RETURN tls_process_server_compressed_certificate(SSL_CONNECTION *sc, PACKET *pkt)
2188
{
2189
    MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
2190
    PACKET tmppkt;
2191
    BUF_MEM *buf = BUF_MEM_new();
2192
2193
    if (tls13_process_compressed_certificate(sc, pkt, &tmppkt, buf) != MSG_PROCESS_ERROR)
2194
        ret = tls_process_server_certificate(sc, &tmppkt);
2195
2196
    BUF_MEM_free(buf);
2197
    return ret;
2198
}
2199
#endif
2200
2201
static int tls_process_ske_psk_preamble(SSL_CONNECTION *s, PACKET *pkt)
2202
0
{
2203
0
#ifndef OPENSSL_NO_PSK
2204
0
    PACKET psk_identity_hint;
2205
2206
    /* PSK ciphersuites are preceded by an identity hint */
2207
2208
0
    if (!PACKET_get_length_prefixed_2(pkt, &psk_identity_hint)) {
2209
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2210
0
        return 0;
2211
0
    }
2212
2213
    /*
2214
     * Store PSK identity hint for later use, hint is used in
2215
     * tls_construct_client_key_exchange.  Assume that the maximum length of
2216
     * a PSK identity hint can be as long as the maximum length of a PSK
2217
     * identity.
2218
     */
2219
0
    if (PACKET_remaining(&psk_identity_hint) > PSK_MAX_IDENTITY_LEN) {
2220
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DATA_LENGTH_TOO_LONG);
2221
0
        return 0;
2222
0
    }
2223
2224
0
    if (PACKET_remaining(&psk_identity_hint) == 0) {
2225
0
        OPENSSL_free(s->session->psk_identity_hint);
2226
0
        s->session->psk_identity_hint = NULL;
2227
0
    } else if (!PACKET_strndup(&psk_identity_hint,
2228
0
                               &s->session->psk_identity_hint)) {
2229
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2230
0
        return 0;
2231
0
    }
2232
2233
0
    return 1;
2234
#else
2235
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2236
    return 0;
2237
#endif
2238
0
}
2239
2240
static int tls_process_ske_srp(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)
2241
0
{
2242
0
#ifndef OPENSSL_NO_SRP
2243
0
    PACKET prime, generator, salt, server_pub;
2244
2245
0
    if (!PACKET_get_length_prefixed_2(pkt, &prime)
2246
0
        || !PACKET_get_length_prefixed_2(pkt, &generator)
2247
0
        || !PACKET_get_length_prefixed_1(pkt, &salt)
2248
0
        || !PACKET_get_length_prefixed_2(pkt, &server_pub)) {
2249
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2250
0
        return 0;
2251
0
    }
2252
2253
0
    if ((s->srp_ctx.N =
2254
0
         BN_bin2bn(PACKET_data(&prime),
2255
0
                   (int)PACKET_remaining(&prime), NULL)) == NULL
2256
0
        || (s->srp_ctx.g =
2257
0
            BN_bin2bn(PACKET_data(&generator),
2258
0
                      (int)PACKET_remaining(&generator), NULL)) == NULL
2259
0
        || (s->srp_ctx.s =
2260
0
            BN_bin2bn(PACKET_data(&salt),
2261
0
                      (int)PACKET_remaining(&salt), NULL)) == NULL
2262
0
        || (s->srp_ctx.B =
2263
0
            BN_bin2bn(PACKET_data(&server_pub),
2264
0
                      (int)PACKET_remaining(&server_pub), NULL)) == NULL) {
2265
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
2266
0
        return 0;
2267
0
    }
2268
2269
0
    if (!srp_verify_server_param(s)) {
2270
        /* SSLfatal() already called */
2271
0
        return 0;
2272
0
    }
2273
2274
    /* We must check if there is a certificate */
2275
0
    if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
2276
0
        *pkey = tls_get_peer_pkey(s);
2277
2278
0
    return 1;
2279
#else
2280
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2281
    return 0;
2282
#endif
2283
0
}
2284
2285
static int tls_process_ske_dhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)
2286
10.8k
{
2287
10.8k
    PACKET prime, generator, pub_key;
2288
10.8k
    EVP_PKEY *peer_tmp = NULL;
2289
10.8k
    BIGNUM *p = NULL, *g = NULL, *bnpub_key = NULL;
2290
10.8k
    EVP_PKEY_CTX *pctx = NULL;
2291
10.8k
    OSSL_PARAM *params = NULL;
2292
10.8k
    OSSL_PARAM_BLD *tmpl = NULL;
2293
10.8k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2294
10.8k
    int ret = 0;
2295
2296
10.8k
    if (!PACKET_get_length_prefixed_2(pkt, &prime)
2297
10.7k
        || !PACKET_get_length_prefixed_2(pkt, &generator)
2298
10.5k
        || !PACKET_get_length_prefixed_2(pkt, &pub_key)) {
2299
341
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2300
341
        return 0;
2301
341
    }
2302
2303
10.4k
    p = BN_bin2bn(PACKET_data(&prime), (int)PACKET_remaining(&prime), NULL);
2304
10.4k
    g = BN_bin2bn(PACKET_data(&generator), (int)PACKET_remaining(&generator),
2305
10.4k
                  NULL);
2306
10.4k
    bnpub_key = BN_bin2bn(PACKET_data(&pub_key),
2307
10.4k
                          (int)PACKET_remaining(&pub_key), NULL);
2308
10.4k
    if (p == NULL || g == NULL || bnpub_key == NULL) {
2309
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BN_LIB);
2310
0
        goto err;
2311
0
    }
2312
2313
10.4k
    tmpl = OSSL_PARAM_BLD_new();
2314
10.4k
    if (tmpl == NULL
2315
10.4k
            || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_P, p)
2316
10.4k
            || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_FFC_G, g)
2317
10.4k
            || !OSSL_PARAM_BLD_push_BN(tmpl, OSSL_PKEY_PARAM_PUB_KEY,
2318
10.4k
                                       bnpub_key)
2319
10.4k
            || (params = OSSL_PARAM_BLD_to_param(tmpl)) == NULL) {
2320
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2321
0
        goto err;
2322
0
    }
2323
2324
10.4k
    pctx = EVP_PKEY_CTX_new_from_name(sctx->libctx, "DH", sctx->propq);
2325
10.4k
    if (pctx == NULL) {
2326
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2327
0
        goto err;
2328
0
    }
2329
10.4k
    if (EVP_PKEY_fromdata_init(pctx) <= 0
2330
10.4k
            || EVP_PKEY_fromdata(pctx, &peer_tmp, EVP_PKEY_KEYPAIR, params) <= 0) {
2331
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_DH_VALUE);
2332
0
        goto err;
2333
0
    }
2334
2335
10.4k
    EVP_PKEY_CTX_free(pctx);
2336
10.4k
    pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, peer_tmp, sctx->propq);
2337
10.4k
    if (pctx == NULL
2338
            /*
2339
             * EVP_PKEY_param_check() will verify that the DH params are using
2340
             * a safe prime. In this context, because we're using ephemeral DH,
2341
             * we're ok with it not being a safe prime.
2342
             * EVP_PKEY_param_check_quick() skips the safe prime check.
2343
             */
2344
10.4k
            || EVP_PKEY_param_check_quick(pctx) != 1
2345
8.10k
            || EVP_PKEY_public_check(pctx) != 1) {
2346
2.66k
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_DH_VALUE);
2347
2.66k
        goto err;
2348
2.66k
    }
2349
2350
7.79k
    if (!ssl_security(s, SSL_SECOP_TMP_DH,
2351
7.79k
                      EVP_PKEY_get_security_bits(peer_tmp),
2352
7.79k
                      0, peer_tmp)) {
2353
15
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_DH_KEY_TOO_SMALL);
2354
15
        goto err;
2355
15
    }
2356
2357
7.77k
    s->s3.peer_tmp = peer_tmp;
2358
7.77k
    peer_tmp = NULL;
2359
2360
    /*
2361
     * FIXME: This makes assumptions about which ciphersuites come with
2362
     * public keys. We should have a less ad-hoc way of doing this
2363
     */
2364
7.77k
    if (s->s3.tmp.new_cipher->algorithm_auth & (SSL_aRSA | SSL_aDSS))
2365
3.42k
        *pkey = tls_get_peer_pkey(s);
2366
    /* else anonymous DH, so no certificate or pkey. */
2367
2368
7.77k
    ret = 1;
2369
2370
10.4k
 err:
2371
10.4k
    OSSL_PARAM_BLD_free(tmpl);
2372
10.4k
    OSSL_PARAM_free(params);
2373
10.4k
    EVP_PKEY_free(peer_tmp);
2374
10.4k
    EVP_PKEY_CTX_free(pctx);
2375
10.4k
    BN_free(p);
2376
10.4k
    BN_free(g);
2377
10.4k
    BN_free(bnpub_key);
2378
2379
10.4k
    return ret;
2380
7.77k
}
2381
2382
static int tls_process_ske_ecdhe(SSL_CONNECTION *s, PACKET *pkt, EVP_PKEY **pkey)
2383
8.70k
{
2384
8.70k
    PACKET encoded_pt;
2385
8.70k
    unsigned int curve_type, curve_id;
2386
2387
    /*
2388
     * Extract elliptic curve parameters and the server's ephemeral ECDH
2389
     * public key. We only support named (not generic) curves and
2390
     * ECParameters in this case is just three bytes.
2391
     */
2392
8.70k
    if (!PACKET_get_1(pkt, &curve_type) || !PACKET_get_net_2(pkt, &curve_id)) {
2393
26
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
2394
26
        return 0;
2395
26
    }
2396
    /*
2397
     * Check curve is named curve type and one of our preferences, if not
2398
     * server has sent an invalid curve.
2399
     */
2400
8.67k
    if (curve_type != NAMED_CURVE_TYPE
2401
8.65k
            || !tls1_check_group_id(s, curve_id, 1)) {
2402
196
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_WRONG_CURVE);
2403
196
        return 0;
2404
196
    }
2405
2406
8.48k
    if ((s->s3.peer_tmp = ssl_generate_param_group(s, curve_id)) == NULL) {
2407
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2408
0
                 SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
2409
0
        return 0;
2410
0
    }
2411
2412
8.48k
    if (!PACKET_get_length_prefixed_1(pkt, &encoded_pt)) {
2413
74
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2414
74
        return 0;
2415
74
    }
2416
2417
8.40k
    if (EVP_PKEY_set1_encoded_public_key(s->s3.peer_tmp,
2418
8.40k
                                         PACKET_data(&encoded_pt),
2419
8.40k
                                         PACKET_remaining(&encoded_pt)) <= 0) {
2420
1.09k
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_ECPOINT);
2421
1.09k
        return 0;
2422
1.09k
    }
2423
2424
    /*
2425
     * The ECC/TLS specification does not mention the use of DSA to sign
2426
     * ECParameters in the server key exchange message. We do support RSA
2427
     * and ECDSA.
2428
     */
2429
7.31k
    if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aECDSA)
2430
1.42k
        *pkey = tls_get_peer_pkey(s);
2431
5.88k
    else if (s->s3.tmp.new_cipher->algorithm_auth & SSL_aRSA)
2432
868
        *pkey = tls_get_peer_pkey(s);
2433
    /* else anonymous ECDH, so no certificate or pkey. */
2434
2435
    /* Cache the agreed upon group in the SSL_SESSION */
2436
7.31k
    s->session->kex_group = curve_id;
2437
7.31k
    return 1;
2438
8.40k
}
2439
2440
MSG_PROCESS_RETURN tls_process_key_exchange(SSL_CONNECTION *s, PACKET *pkt)
2441
19.5k
{
2442
19.5k
    long alg_k;
2443
19.5k
    EVP_PKEY *pkey = NULL;
2444
19.5k
    EVP_MD_CTX *md_ctx = NULL;
2445
19.5k
    EVP_PKEY_CTX *pctx = NULL;
2446
19.5k
    PACKET save_param_start, signature;
2447
19.5k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2448
2449
19.5k
    alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
2450
2451
19.5k
    save_param_start = *pkt;
2452
2453
19.5k
    EVP_PKEY_free(s->s3.peer_tmp);
2454
19.5k
    s->s3.peer_tmp = NULL;
2455
2456
19.5k
    if (alg_k & SSL_PSK) {
2457
0
        if (!tls_process_ske_psk_preamble(s, pkt)) {
2458
            /* SSLfatal() already called */
2459
0
            goto err;
2460
0
        }
2461
0
    }
2462
2463
    /* Nothing else to do for plain PSK or RSAPSK */
2464
19.5k
    if (alg_k & (SSL_kPSK | SSL_kRSAPSK)) {
2465
19.5k
    } else if (alg_k & SSL_kSRP) {
2466
0
        if (!tls_process_ske_srp(s, pkt, &pkey)) {
2467
            /* SSLfatal() already called */
2468
0
            goto err;
2469
0
        }
2470
19.5k
    } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
2471
10.8k
        if (!tls_process_ske_dhe(s, pkt, &pkey)) {
2472
            /* SSLfatal() already called */
2473
3.02k
            goto err;
2474
3.02k
        }
2475
10.8k
    } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
2476
8.70k
        if (!tls_process_ske_ecdhe(s, pkt, &pkey)) {
2477
            /* SSLfatal() already called */
2478
1.39k
            goto err;
2479
1.39k
        }
2480
8.70k
    } else if (alg_k) {
2481
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
2482
0
        goto err;
2483
0
    }
2484
2485
    /* if it was signed, check the signature */
2486
15.0k
    if (pkey != NULL) {
2487
5.72k
        PACKET params;
2488
5.72k
        const EVP_MD *md = NULL;
2489
5.72k
        unsigned char *tbs;
2490
5.72k
        size_t tbslen;
2491
5.72k
        int rv;
2492
2493
        /*
2494
         * |pkt| now points to the beginning of the signature, so the difference
2495
         * equals the length of the parameters.
2496
         */
2497
5.72k
        if (!PACKET_get_sub_packet(&save_param_start, &params,
2498
5.72k
                                   PACKET_remaining(&save_param_start) -
2499
5.72k
                                   PACKET_remaining(pkt))) {
2500
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, ERR_R_INTERNAL_ERROR);
2501
0
            goto err;
2502
0
        }
2503
2504
5.72k
        if (SSL_USE_SIGALGS(s)) {
2505
3.98k
            unsigned int sigalg;
2506
2507
3.98k
            if (!PACKET_get_net_2(pkt, &sigalg)) {
2508
21
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_TOO_SHORT);
2509
21
                goto err;
2510
21
            }
2511
3.96k
            if (tls12_check_peer_sigalg(s, sigalg, pkey) <=0) {
2512
                /* SSLfatal() already called */
2513
195
                goto err;
2514
195
            }
2515
3.96k
        } else if (!tls1_set_peer_legacy_sigalg(s, pkey)) {
2516
9
            SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2517
9
                     SSL_R_LEGACY_SIGALG_DISALLOWED_OR_UNSUPPORTED);
2518
9
            goto err;
2519
9
        }
2520
2521
5.49k
        if (!tls1_lookup_md(sctx, s->s3.tmp.peer_sigalg, &md)) {
2522
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2523
0
                     SSL_R_NO_SUITABLE_DIGEST_ALGORITHM);
2524
0
            goto err;
2525
0
        }
2526
5.49k
        if (SSL_USE_SIGALGS(s))
2527
5.49k
            OSSL_TRACE1(TLS, "USING TLSv1.2 HASH %s\n",
2528
5.49k
                        md == NULL ? "n/a" : EVP_MD_get0_name(md));
2529
2530
5.49k
        if (!PACKET_get_length_prefixed_2(pkt, &signature)
2531
5.38k
            || PACKET_remaining(pkt) != 0) {
2532
167
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2533
167
            goto err;
2534
167
        }
2535
2536
5.32k
        md_ctx = EVP_MD_CTX_new();
2537
5.32k
        if (md_ctx == NULL) {
2538
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2539
0
            goto err;
2540
0
        }
2541
2542
5.32k
        if (EVP_DigestVerifyInit_ex(md_ctx, &pctx,
2543
5.32k
                                    md == NULL ? NULL : EVP_MD_get0_name(md),
2544
5.32k
                                    sctx->libctx, sctx->propq, pkey,
2545
5.32k
                                    NULL) <= 0) {
2546
31
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2547
31
            goto err;
2548
31
        }
2549
5.29k
        if (SSL_USE_PSS(s)) {
2550
512
            if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2551
512
                || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx,
2552
512
                                                RSA_PSS_SALTLEN_DIGEST) <= 0) {
2553
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2554
0
                goto err;
2555
0
            }
2556
512
        }
2557
5.29k
        tbslen = construct_key_exchange_tbs(s, &tbs, PACKET_data(&params),
2558
5.29k
                                            PACKET_remaining(&params));
2559
5.29k
        if (tbslen == 0) {
2560
            /* SSLfatal() already called */
2561
0
            goto err;
2562
0
        }
2563
2564
5.29k
        rv = EVP_DigestVerify(md_ctx, PACKET_data(&signature),
2565
5.29k
                              PACKET_remaining(&signature), tbs, tbslen);
2566
5.29k
        OPENSSL_free(tbs);
2567
5.29k
        if (rv <= 0) {
2568
5.21k
            SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_R_BAD_SIGNATURE);
2569
5.21k
            goto err;
2570
5.21k
        }
2571
79
        EVP_MD_CTX_free(md_ctx);
2572
79
        md_ctx = NULL;
2573
9.37k
    } else {
2574
        /* aNULL, aSRP or PSK do not need public keys */
2575
9.37k
        if (!(s->s3.tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
2576
0
            && !(alg_k & SSL_PSK)) {
2577
            /* Might be wrong key type, check it */
2578
0
            if (ssl3_check_cert_and_algorithm(s)) {
2579
0
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_DATA);
2580
0
            }
2581
            /* else this shouldn't happen, SSLfatal() already called */
2582
0
            goto err;
2583
0
        }
2584
        /* still data left over */
2585
9.37k
        if (PACKET_remaining(pkt) != 0) {
2586
501
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_EXTRA_DATA_IN_MESSAGE);
2587
501
            goto err;
2588
501
        }
2589
9.37k
    }
2590
2591
8.94k
    return MSG_PROCESS_CONTINUE_READING;
2592
10.5k
 err:
2593
10.5k
    EVP_MD_CTX_free(md_ctx);
2594
10.5k
    return MSG_PROCESS_ERROR;
2595
15.0k
}
2596
2597
MSG_PROCESS_RETURN tls_process_certificate_request(SSL_CONNECTION *s,
2598
                                                   PACKET *pkt)
2599
833
{
2600
    /* Clear certificate validity flags */
2601
833
    if (s->s3.tmp.valid_flags != NULL)
2602
0
        memset(s->s3.tmp.valid_flags, 0, s->ssl_pkey_num * sizeof(uint32_t));
2603
833
    else
2604
833
        s->s3.tmp.valid_flags = OPENSSL_calloc(s->ssl_pkey_num, sizeof(uint32_t));
2605
2606
    /* Give up for good if allocation didn't work */
2607
833
    if (s->s3.tmp.valid_flags == NULL)
2608
0
        return 0;
2609
2610
833
    if (SSL_CONNECTION_IS_TLS13(s)) {
2611
186
        PACKET reqctx, extensions;
2612
186
        RAW_EXTENSION *rawexts = NULL;
2613
2614
186
        if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
2615
            /*
2616
             * We already sent close_notify. This can only happen in TLSv1.3
2617
             * post-handshake messages. We can't reasonably respond to this, so
2618
             * we just ignore it
2619
             */
2620
0
            return MSG_PROCESS_FINISHED_READING;
2621
0
        }
2622
2623
        /* Free and zero certificate types: it is not present in TLS 1.3 */
2624
186
        OPENSSL_free(s->s3.tmp.ctype);
2625
186
        s->s3.tmp.ctype = NULL;
2626
186
        s->s3.tmp.ctype_len = 0;
2627
186
        OPENSSL_free(s->pha_context);
2628
186
        s->pha_context = NULL;
2629
186
        s->pha_context_len = 0;
2630
2631
186
        if (!PACKET_get_length_prefixed_1(pkt, &reqctx) ||
2632
174
            !PACKET_memdup(&reqctx, &s->pha_context, &s->pha_context_len)) {
2633
12
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2634
12
            return MSG_PROCESS_ERROR;
2635
12
        }
2636
2637
174
        if (!PACKET_get_length_prefixed_2(pkt, &extensions)) {
2638
16
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_LENGTH);
2639
16
            return MSG_PROCESS_ERROR;
2640
16
        }
2641
158
        if (!tls_collect_extensions(s, &extensions,
2642
158
                                    SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
2643
158
                                    &rawexts, NULL, 1)
2644
135
            || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE_REQUEST,
2645
158
                                         rawexts, NULL, 0, 1)) {
2646
            /* SSLfatal() already called */
2647
158
            OPENSSL_free(rawexts);
2648
158
            return MSG_PROCESS_ERROR;
2649
158
        }
2650
0
        OPENSSL_free(rawexts);
2651
0
        if (!tls1_process_sigalgs(s)) {
2652
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
2653
0
            return MSG_PROCESS_ERROR;
2654
0
        }
2655
647
    } else {
2656
647
        PACKET ctypes;
2657
2658
        /* get the certificate types */
2659
647
        if (!PACKET_get_length_prefixed_1(pkt, &ctypes)) {
2660
19
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2661
19
            return MSG_PROCESS_ERROR;
2662
19
        }
2663
2664
628
        if (!PACKET_memdup(&ctypes, &s->s3.tmp.ctype, &s->s3.tmp.ctype_len)) {
2665
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2666
0
            return MSG_PROCESS_ERROR;
2667
0
        }
2668
2669
628
        if (SSL_USE_SIGALGS(s)) {
2670
585
            PACKET sigalgs;
2671
2672
585
            if (!PACKET_get_length_prefixed_2(pkt, &sigalgs)) {
2673
49
                SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2674
49
                return MSG_PROCESS_ERROR;
2675
49
            }
2676
2677
            /*
2678
             * Despite this being for certificates, preserve compatibility
2679
             * with pre-TLS 1.3 and use the regular sigalgs field.
2680
             */
2681
536
            if (!tls1_save_sigalgs(s, &sigalgs, 0)) {
2682
21
                SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2683
21
                         SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2684
21
                return MSG_PROCESS_ERROR;
2685
21
            }
2686
515
            if (!tls1_process_sigalgs(s)) {
2687
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
2688
0
                return MSG_PROCESS_ERROR;
2689
0
            }
2690
515
        }
2691
2692
        /* get the CA RDNs */
2693
558
        if (!parse_ca_names(s, pkt)) {
2694
            /* SSLfatal() already called */
2695
475
            return MSG_PROCESS_ERROR;
2696
475
        }
2697
558
    }
2698
2699
83
    if (PACKET_remaining(pkt) != 0) {
2700
39
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2701
39
        return MSG_PROCESS_ERROR;
2702
39
    }
2703
2704
    /* we should setup a certificate to return.... */
2705
44
    s->s3.tmp.cert_req = 1;
2706
2707
    /*
2708
     * In TLSv1.3 we don't prepare the client certificate yet. We wait until
2709
     * after the CertificateVerify message has been received. This is because
2710
     * in TLSv1.3 the CertificateRequest arrives before the Certificate message
2711
     * but in TLSv1.2 it is the other way around. We want to make sure that
2712
     * SSL_get1_peer_certificate() returns something sensible in
2713
     * client_cert_cb.
2714
     */
2715
44
    if (SSL_CONNECTION_IS_TLS13(s)
2716
0
        && s->post_handshake_auth != SSL_PHA_REQUESTED)
2717
0
        return MSG_PROCESS_CONTINUE_READING;
2718
2719
44
    return MSG_PROCESS_CONTINUE_PROCESSING;
2720
44
}
2721
2722
MSG_PROCESS_RETURN tls_process_new_session_ticket(SSL_CONNECTION *s,
2723
                                                  PACKET *pkt)
2724
1.32k
{
2725
1.32k
    unsigned int ticklen;
2726
1.32k
    unsigned long ticket_lifetime_hint, age_add = 0;
2727
1.32k
    unsigned int sess_len;
2728
1.32k
    RAW_EXTENSION *exts = NULL;
2729
1.32k
    PACKET nonce;
2730
1.32k
    EVP_MD *sha256 = NULL;
2731
1.32k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2732
2733
1.32k
    PACKET_null_init(&nonce);
2734
2735
1.32k
    if (!PACKET_get_net_4(pkt, &ticket_lifetime_hint)
2736
1.30k
        || (SSL_CONNECTION_IS_TLS13(s)
2737
1.08k
            && (!PACKET_get_net_4(pkt, &age_add)
2738
1.08k
                || !PACKET_get_length_prefixed_1(pkt, &nonce)))
2739
1.29k
        || !PACKET_get_net_2(pkt, &ticklen)
2740
1.28k
        || (SSL_CONNECTION_IS_TLS13(s) ? (ticklen == 0
2741
1.06k
                                          || PACKET_remaining(pkt) < ticklen)
2742
1.28k
                                       : PACKET_remaining(pkt) != ticklen)) {
2743
107
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2744
107
        goto err;
2745
107
    }
2746
2747
    /*
2748
     * Server is allowed to change its mind (in <=TLSv1.2) and send an empty
2749
     * ticket. We already checked this TLSv1.3 case above, so it should never
2750
     * be 0 here in that instance
2751
     */
2752
1.22k
    if (ticklen == 0)
2753
11
        return MSG_PROCESS_CONTINUE_READING;
2754
2755
    /*
2756
     * Sessions must be immutable once they go into the session cache. Otherwise
2757
     * we can get multi-thread problems. Therefore we don't "update" sessions,
2758
     * we replace them with a duplicate. In TLSv1.3 we need to do this every
2759
     * time a NewSessionTicket arrives because those messages arrive
2760
     * post-handshake and the session may have already gone into the session
2761
     * cache.
2762
     */
2763
1.20k
    if (SSL_CONNECTION_IS_TLS13(s) || s->session->session_id_length > 0) {
2764
1.06k
        SSL_SESSION *new_sess;
2765
2766
        /*
2767
         * We reused an existing session, so we need to replace it with a new
2768
         * one
2769
         */
2770
1.06k
        if ((new_sess = ssl_session_dup(s->session, 0)) == 0) {
2771
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
2772
0
            goto err;
2773
0
        }
2774
2775
1.06k
        if ((s->session_ctx->session_cache_mode & SSL_SESS_CACHE_CLIENT) != 0
2776
0
                && !SSL_CONNECTION_IS_TLS13(s)) {
2777
            /*
2778
             * In TLSv1.2 and below the arrival of a new tickets signals that
2779
             * any old ticket we were using is now out of date, so we remove the
2780
             * old session from the cache. We carry on if this fails
2781
             */
2782
0
            SSL_CTX_remove_session(s->session_ctx, s->session);
2783
0
        }
2784
2785
1.06k
        SSL_SESSION_free(s->session);
2786
1.06k
        s->session = new_sess;
2787
1.06k
    }
2788
2789
1.20k
    s->session->time = ossl_time_now();
2790
1.20k
    ssl_session_calculate_timeout(s->session);
2791
2792
1.20k
    OPENSSL_free(s->session->ext.tick);
2793
1.20k
    s->session->ext.tick = NULL;
2794
1.20k
    s->session->ext.ticklen = 0;
2795
2796
1.20k
    s->session->ext.tick = OPENSSL_malloc(ticklen);
2797
1.20k
    if (s->session->ext.tick == NULL) {
2798
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2799
0
        goto err;
2800
0
    }
2801
1.20k
    if (!PACKET_copy_bytes(pkt, s->session->ext.tick, ticklen)) {
2802
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2803
0
        goto err;
2804
0
    }
2805
2806
1.20k
    s->session->ext.tick_lifetime_hint = ticket_lifetime_hint;
2807
1.20k
    s->session->ext.tick_age_add = age_add;
2808
1.20k
    s->session->ext.ticklen = ticklen;
2809
2810
1.20k
    if (SSL_CONNECTION_IS_TLS13(s)) {
2811
1.05k
        PACKET extpkt;
2812
2813
1.05k
        if (!PACKET_as_length_prefixed_2(pkt, &extpkt)
2814
1.01k
                || PACKET_remaining(pkt) != 0) {
2815
44
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2816
44
            goto err;
2817
44
        }
2818
2819
1.01k
        if (!tls_collect_extensions(s, &extpkt,
2820
1.01k
                                    SSL_EXT_TLS1_3_NEW_SESSION_TICKET, &exts,
2821
1.01k
                                    NULL, 1)
2822
1.00k
                || !tls_parse_all_extensions(s,
2823
1.00k
                                             SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
2824
1.00k
                                             exts, NULL, 0, 1)) {
2825
            /* SSLfatal() already called */
2826
4
            goto err;
2827
4
        }
2828
1.01k
    }
2829
2830
    /*
2831
     * There are two ways to detect a resumed ticket session. One is to set
2832
     * an appropriate session ID and then the server must return a match in
2833
     * ServerHello. This allows the normal client session ID matching to work
2834
     * and we know much earlier that the ticket has been accepted. The
2835
     * other way is to set zero length session ID when the ticket is
2836
     * presented and rely on the handshake to determine session resumption.
2837
     * We choose the former approach because this fits in with assumptions
2838
     * elsewhere in OpenSSL. The session ID is set to the SHA256 hash of the
2839
     * ticket.
2840
     */
2841
1.16k
    sha256 = EVP_MD_fetch(sctx->libctx, "SHA2-256", sctx->propq);
2842
1.16k
    if (sha256 == NULL) {
2843
        /* Error is already recorded */
2844
0
        SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
2845
0
        goto err;
2846
0
    }
2847
    /*
2848
     * We use sess_len here because EVP_Digest expects an int
2849
     * but s->session->session_id_length is a size_t
2850
     */
2851
1.16k
    if (!EVP_Digest(s->session->ext.tick, ticklen,
2852
1.16k
                    s->session->session_id, &sess_len,
2853
1.16k
                    sha256, NULL)) {
2854
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
2855
0
        goto err;
2856
0
    }
2857
1.16k
    EVP_MD_free(sha256);
2858
1.16k
    sha256 = NULL;
2859
1.16k
    s->session->session_id_length = sess_len;
2860
1.16k
    s->session->not_resumable = 0;
2861
2862
    /* This is a standalone message in TLSv1.3, so there is no more to read */
2863
1.16k
    if (SSL_CONNECTION_IS_TLS13(s)) {
2864
1.00k
        const EVP_MD *md = ssl_handshake_md(s);
2865
1.00k
        int hashleni = EVP_MD_get_size(md);
2866
1.00k
        size_t hashlen;
2867
        /* ASCII: "resumption", in hex for EBCDIC compatibility */
2868
1.00k
        static const unsigned char nonce_label[] = { 0x72, 0x65, 0x73, 0x75, 0x6D,
2869
1.00k
                                                     0x70, 0x74, 0x69, 0x6F, 0x6E };
2870
2871
        /* Ensure cast to size_t is safe */
2872
1.00k
        if (!ossl_assert(hashleni > 0)) {
2873
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
2874
0
            goto err;
2875
0
        }
2876
1.00k
        hashlen = (size_t)hashleni;
2877
2878
1.00k
        if (!tls13_hkdf_expand(s, md, s->resumption_master_secret,
2879
1.00k
                               nonce_label,
2880
1.00k
                               sizeof(nonce_label),
2881
1.00k
                               PACKET_data(&nonce),
2882
1.00k
                               PACKET_remaining(&nonce),
2883
1.00k
                               s->session->master_key,
2884
1.00k
                               hashlen, 1)) {
2885
            /* SSLfatal() already called */
2886
0
            goto err;
2887
0
        }
2888
1.00k
        s->session->master_key_length = hashlen;
2889
2890
1.00k
        OPENSSL_free(exts);
2891
1.00k
        ssl_update_cache(s, SSL_SESS_CACHE_CLIENT);
2892
1.00k
        return MSG_PROCESS_FINISHED_READING;
2893
1.00k
    }
2894
2895
155
    return MSG_PROCESS_CONTINUE_READING;
2896
155
 err:
2897
155
    EVP_MD_free(sha256);
2898
155
    OPENSSL_free(exts);
2899
155
    return MSG_PROCESS_ERROR;
2900
1.16k
}
2901
2902
/*
2903
 * In TLSv1.3 this is called from the extensions code, otherwise it is used to
2904
 * parse a separate message. Returns 1 on success or 0 on failure
2905
 */
2906
int tls_process_cert_status_body(SSL_CONNECTION *s, size_t chainidx, PACKET *pkt)
2907
0
{
2908
0
    unsigned int type;
2909
0
#ifndef OPENSSL_NO_OCSP
2910
0
    size_t resplen;
2911
0
    unsigned char *respder;
2912
0
    OCSP_RESPONSE *resp = NULL;
2913
0
    const unsigned char *p;
2914
0
#endif
2915
2916
0
    if (!PACKET_get_1(pkt, &type)
2917
0
        || type != TLSEXT_STATUSTYPE_ocsp) {
2918
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_UNSUPPORTED_STATUS_TYPE);
2919
0
        return 0;
2920
0
    }
2921
2922
0
#ifndef OPENSSL_NO_OCSP
2923
0
    OPENSSL_free(s->ext.ocsp.resp);
2924
0
    s->ext.ocsp.resp = NULL;
2925
0
    s->ext.ocsp.resp_len = 0;
2926
2927
0
    if (s->ext.ocsp.resp_ex == NULL)
2928
0
        s->ext.ocsp.resp_ex = sk_OCSP_RESPONSE_new_null();
2929
2930
    /*
2931
     * TODO(DTLS-1.3): in future DTLS should also be considered
2932
     */
2933
0
    if (!SSL_CONNECTION_IS_TLS13(s) && type == TLSEXT_STATUSTYPE_ocsp) {
2934
0
        sk_OCSP_RESPONSE_pop_free(s->ext.ocsp.resp_ex, OCSP_RESPONSE_free);
2935
0
        s->ext.ocsp.resp_ex = sk_OCSP_RESPONSE_new_null();
2936
0
    }
2937
2938
0
    if (PACKET_remaining(pkt) > 0) {
2939
0
        if (!PACKET_get_net_3_len(pkt, &resplen)
2940
0
            || PACKET_remaining(pkt) != resplen) {
2941
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2942
0
            return 0;
2943
0
        }
2944
2945
0
        if (resplen == 0) {
2946
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_BAD_PACKET);
2947
0
            return 0;
2948
0
        }
2949
2950
0
        if ((respder = OPENSSL_malloc(resplen)) == NULL) {
2951
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
2952
0
            return 0;
2953
0
        }
2954
2955
0
        if (!PACKET_copy_bytes(pkt, respder, resplen)) {
2956
0
            SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
2957
0
            OPENSSL_free(respder);
2958
0
            return 0;
2959
0
        }
2960
0
        p = respder;
2961
0
        resp = d2i_OCSP_RESPONSE(NULL, &p, (long)resplen);
2962
0
        OPENSSL_free(respder);
2963
0
        if (resp == NULL) {
2964
0
            SSLfatal(s, TLS1_AD_BAD_CERTIFICATE_STATUS_RESPONSE,
2965
0
                     SSL_R_TLSV1_BAD_CERTIFICATE_STATUS_RESPONSE);
2966
0
            return 0;
2967
0
        }
2968
0
        sk_OCSP_RESPONSE_insert(s->ext.ocsp.resp_ex, resp, (int)chainidx);
2969
0
    }
2970
2971
0
#endif
2972
0
    return 1;
2973
0
}
2974
2975
MSG_PROCESS_RETURN tls_process_cert_status(SSL_CONNECTION *s, PACKET *pkt)
2976
0
{
2977
0
    if (!tls_process_cert_status_body(s, 0, pkt)) {
2978
        /* SSLfatal() already called */
2979
0
        return MSG_PROCESS_ERROR;
2980
0
    }
2981
2982
0
    return MSG_PROCESS_CONTINUE_READING;
2983
0
}
2984
2985
/*
2986
 * Perform miscellaneous checks and processing after we have received the
2987
 * server's initial flight. In TLS1.3 this is after the Server Finished message.
2988
 * In <=TLS1.2 this is after the ServerDone message. Returns 1 on success or 0
2989
 * on failure.
2990
 */
2991
int tls_process_initial_server_flight(SSL_CONNECTION *s)
2992
27.0k
{
2993
27.0k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
2994
2995
    /*
2996
     * at this point we check that we have the required stuff from
2997
     * the server
2998
     */
2999
27.0k
    if (!ssl3_check_cert_and_algorithm(s)) {
3000
        /* SSLfatal() already called */
3001
11
        return 0;
3002
11
    }
3003
3004
    /*
3005
     * Call the ocsp status callback if needed. The |ext.ocsp.resp| and
3006
     * |ext.ocsp.resp_len| values will be set if we actually received a status
3007
     * message, or NULL and -1 otherwise
3008
     */
3009
27.0k
    if (s->ext.status_type != TLSEXT_STATUSTYPE_nothing
3010
0
            && sctx->ext.status_cb != NULL) {
3011
0
        int ret = sctx->ext.status_cb(SSL_CONNECTION_GET_USER_SSL(s),
3012
0
                                      sctx->ext.status_arg);
3013
3014
0
        if (ret == 0) {
3015
0
            SSLfatal(s, SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE,
3016
0
                     SSL_R_INVALID_STATUS_RESPONSE);
3017
0
            return 0;
3018
0
        }
3019
0
        if (ret < 0) {
3020
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3021
0
                     SSL_R_OCSP_CALLBACK_FAILURE);
3022
0
            return 0;
3023
0
        }
3024
0
    }
3025
27.0k
#ifndef OPENSSL_NO_CT
3026
27.0k
    if (s->ct_validation_callback != NULL) {
3027
        /* Note we validate the SCTs whether or not we abort on error */
3028
0
        if (!ssl_validate_ct(s) && (s->verify_mode & SSL_VERIFY_PEER)) {
3029
            /* SSLfatal() already called */
3030
0
            return 0;
3031
0
        }
3032
0
    }
3033
27.0k
#endif
3034
3035
27.0k
    return 1;
3036
27.0k
}
3037
3038
MSG_PROCESS_RETURN tls_process_server_done(SSL_CONNECTION *s, PACKET *pkt)
3039
13.5k
{
3040
13.5k
    if (PACKET_remaining(pkt) > 0) {
3041
        /* should contain no data */
3042
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
3043
0
        return MSG_PROCESS_ERROR;
3044
0
    }
3045
13.5k
#ifndef OPENSSL_NO_SRP
3046
13.5k
    if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
3047
0
        if (ssl_srp_calc_a_param_intern(s) <= 0) {
3048
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_SRP_A_CALC);
3049
0
            return MSG_PROCESS_ERROR;
3050
0
        }
3051
0
    }
3052
13.5k
#endif
3053
3054
13.5k
    if (!tls_process_initial_server_flight(s)) {
3055
        /* SSLfatal() already called */
3056
11
        return MSG_PROCESS_ERROR;
3057
11
    }
3058
3059
13.5k
    return MSG_PROCESS_FINISHED_READING;
3060
13.5k
}
3061
3062
static int tls_construct_cke_psk_preamble(SSL_CONNECTION *s, WPACKET *pkt)
3063
0
{
3064
0
#ifndef OPENSSL_NO_PSK
3065
0
    int ret = 0;
3066
    /*
3067
     * The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes to return a
3068
     * \0-terminated identity. The last byte is for us for simulating
3069
     * strnlen.
3070
     */
3071
0
    char identity[PSK_MAX_IDENTITY_LEN + 1];
3072
0
    size_t identitylen = 0;
3073
0
    unsigned char psk[PSK_MAX_PSK_LEN];
3074
0
    unsigned char *tmppsk = NULL;
3075
0
    char *tmpidentity = NULL;
3076
0
    size_t psklen = 0;
3077
3078
0
    if (s->psk_client_callback == NULL) {
3079
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_PSK_NO_CLIENT_CB);
3080
0
        goto err;
3081
0
    }
3082
3083
0
    memset(identity, 0, sizeof(identity));
3084
3085
0
    psklen = s->psk_client_callback(SSL_CONNECTION_GET_USER_SSL(s),
3086
0
                                    s->session->psk_identity_hint,
3087
0
                                    identity, sizeof(identity) - 1,
3088
0
                                    psk, sizeof(psk));
3089
3090
0
    if (psklen > PSK_MAX_PSK_LEN) {
3091
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, ERR_R_INTERNAL_ERROR);
3092
0
        psklen = PSK_MAX_PSK_LEN;   /* Avoid overrunning the array on cleanse */
3093
0
        goto err;
3094
0
    } else if (psklen == 0) {
3095
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_PSK_IDENTITY_NOT_FOUND);
3096
0
        goto err;
3097
0
    }
3098
3099
0
    identitylen = strlen(identity);
3100
0
    if (identitylen > PSK_MAX_IDENTITY_LEN) {
3101
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3102
0
        goto err;
3103
0
    }
3104
3105
0
    tmppsk = OPENSSL_memdup(psk, psklen);
3106
0
    tmpidentity = OPENSSL_strdup(identity);
3107
0
    if (tmppsk == NULL || tmpidentity == NULL) {
3108
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3109
0
        goto err;
3110
0
    }
3111
3112
0
    OPENSSL_free(s->s3.tmp.psk);
3113
0
    s->s3.tmp.psk = tmppsk;
3114
0
    s->s3.tmp.psklen = psklen;
3115
0
    tmppsk = NULL;
3116
0
    OPENSSL_free(s->session->psk_identity);
3117
0
    s->session->psk_identity = tmpidentity;
3118
0
    tmpidentity = NULL;
3119
3120
0
    if (!WPACKET_sub_memcpy_u16(pkt, identity, identitylen))  {
3121
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3122
0
        goto err;
3123
0
    }
3124
3125
0
    ret = 1;
3126
3127
0
 err:
3128
0
    OPENSSL_cleanse(psk, psklen);
3129
0
    OPENSSL_cleanse(identity, sizeof(identity));
3130
0
    OPENSSL_clear_free(tmppsk, psklen);
3131
0
    OPENSSL_clear_free(tmpidentity, identitylen);
3132
3133
0
    return ret;
3134
#else
3135
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3136
    return 0;
3137
#endif
3138
0
}
3139
3140
static int tls_construct_cke_rsa(SSL_CONNECTION *s, WPACKET *pkt)
3141
5.13k
{
3142
5.13k
    unsigned char *encdata = NULL;
3143
5.13k
    EVP_PKEY *pkey = NULL;
3144
5.13k
    EVP_PKEY_CTX *pctx = NULL;
3145
5.13k
    size_t enclen;
3146
5.13k
    unsigned char *pms = NULL;
3147
5.13k
    size_t pmslen = 0;
3148
5.13k
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3149
3150
5.13k
    if (!received_server_cert(s)) {
3151
        /*
3152
         * We should always have a server certificate with SSL_kRSA.
3153
         */
3154
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3155
0
        return 0;
3156
0
    }
3157
3158
5.13k
    if ((pkey = tls_get_peer_pkey(s)) == NULL) {
3159
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3160
0
        return 0;
3161
0
    }
3162
3163
5.13k
    if (!EVP_PKEY_is_a(pkey, "RSA")) {
3164
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3165
0
        return 0;
3166
0
    }
3167
3168
5.13k
    pmslen = SSL_MAX_MASTER_KEY_LENGTH;
3169
5.13k
    pms = OPENSSL_malloc(pmslen);
3170
5.13k
    if (pms == NULL) {
3171
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3172
0
        return 0;
3173
0
    }
3174
3175
5.13k
    pms[0] = s->client_version >> 8;
3176
5.13k
    pms[1] = s->client_version & 0xff;
3177
5.13k
    if (RAND_bytes_ex(sctx->libctx, pms + 2, pmslen - 2, 0) <= 0) {
3178
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_RAND_LIB);
3179
0
        goto err;
3180
0
    }
3181
3182
    /* Fix buf for TLS and beyond */
3183
5.13k
    if (s->version > SSL3_VERSION && !WPACKET_start_sub_packet_u16(pkt)) {
3184
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3185
0
        goto err;
3186
0
    }
3187
3188
5.13k
    pctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx, pkey, sctx->propq);
3189
5.13k
    if (pctx == NULL || EVP_PKEY_encrypt_init(pctx) <= 0
3190
5.13k
        || EVP_PKEY_encrypt(pctx, NULL, &enclen, pms, pmslen) <= 0) {
3191
8
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3192
8
        goto err;
3193
8
    }
3194
5.12k
    if (!WPACKET_allocate_bytes(pkt, enclen, &encdata)
3195
5.12k
            || EVP_PKEY_encrypt(pctx, encdata, &enclen, pms, pmslen) <= 0) {
3196
590
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_RSA_ENCRYPT);
3197
590
        goto err;
3198
590
    }
3199
4.53k
    EVP_PKEY_CTX_free(pctx);
3200
4.53k
    pctx = NULL;
3201
3202
    /* Fix buf for TLS and beyond */
3203
4.53k
    if (s->version > SSL3_VERSION && !WPACKET_close(pkt)) {
3204
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3205
0
        goto err;
3206
0
    }
3207
3208
    /* Log the premaster secret, if logging is enabled. */
3209
4.53k
    if (!ssl_log_rsa_client_key_exchange(s, encdata, enclen, pms, pmslen)) {
3210
        /* SSLfatal() already called */
3211
0
        goto err;
3212
0
    }
3213
3214
4.53k
    s->s3.tmp.pms = pms;
3215
4.53k
    s->s3.tmp.pmslen = pmslen;
3216
3217
4.53k
    return 1;
3218
598
 err:
3219
598
    OPENSSL_clear_free(pms, pmslen);
3220
598
    EVP_PKEY_CTX_free(pctx);
3221
3222
598
    return 0;
3223
4.53k
}
3224
3225
static int tls_construct_cke_dhe(SSL_CONNECTION *s, WPACKET *pkt)
3226
4.31k
{
3227
4.31k
    EVP_PKEY *ckey = NULL, *skey = NULL;
3228
4.31k
    unsigned char *keybytes = NULL;
3229
4.31k
    int prime_len;
3230
4.31k
    unsigned char *encoded_pub = NULL;
3231
4.31k
    size_t encoded_pub_len, pad_len;
3232
4.31k
    int ret = 0;
3233
3234
4.31k
    skey = s->s3.peer_tmp;
3235
4.31k
    if (skey == NULL) {
3236
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3237
0
        goto err;
3238
0
    }
3239
3240
4.31k
    ckey = ssl_generate_pkey(s, skey);
3241
4.31k
    if (ckey == NULL) {
3242
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3243
0
        goto err;
3244
0
    }
3245
3246
4.31k
    if (ssl_derive(s, ckey, skey, 0) == 0) {
3247
        /* SSLfatal() already called */
3248
0
        goto err;
3249
0
    }
3250
3251
    /* send off the data */
3252
3253
    /* Generate encoding of server key */
3254
4.31k
    encoded_pub_len = EVP_PKEY_get1_encoded_public_key(ckey, &encoded_pub);
3255
4.31k
    if (encoded_pub_len == 0) {
3256
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3257
0
        EVP_PKEY_free(ckey);
3258
0
        return EXT_RETURN_FAIL;
3259
0
    }
3260
3261
    /*
3262
     * For interoperability with some versions of the Microsoft TLS
3263
     * stack, we need to zero pad the DHE pub key to the same length
3264
     * as the prime.
3265
     */
3266
4.31k
    prime_len = EVP_PKEY_get_size(ckey);
3267
4.31k
    pad_len = prime_len - encoded_pub_len;
3268
4.31k
    if (pad_len > 0) {
3269
0
        if (!WPACKET_sub_allocate_bytes_u16(pkt, pad_len, &keybytes)) {
3270
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3271
0
            goto err;
3272
0
        }
3273
0
        memset(keybytes, 0, pad_len);
3274
0
    }
3275
3276
4.31k
    if (!WPACKET_sub_memcpy_u16(pkt, encoded_pub, encoded_pub_len)) {
3277
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3278
0
        goto err;
3279
0
    }
3280
3281
4.31k
    ret = 1;
3282
4.31k
 err:
3283
4.31k
    OPENSSL_free(encoded_pub);
3284
4.31k
    EVP_PKEY_free(ckey);
3285
4.31k
    return ret;
3286
4.31k
}
3287
3288
static int tls_construct_cke_ecdhe(SSL_CONNECTION *s, WPACKET *pkt)
3289
3.85k
{
3290
3.85k
    unsigned char *encodedPoint = NULL;
3291
3.85k
    size_t encoded_pt_len = 0;
3292
3.85k
    EVP_PKEY *ckey = NULL, *skey = NULL;
3293
3.85k
    int ret = 0;
3294
3295
3.85k
    skey = s->s3.peer_tmp;
3296
3.85k
    if (skey == NULL) {
3297
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3298
0
        return 0;
3299
0
    }
3300
3301
3.85k
    ckey = ssl_generate_pkey(s, skey);
3302
3.85k
    if (ckey == NULL) {
3303
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SSL_LIB);
3304
0
        goto err;
3305
0
    }
3306
3307
3.85k
    if (ssl_derive(s, ckey, skey, 0) == 0) {
3308
        /* SSLfatal() already called */
3309
411
        goto err;
3310
411
    }
3311
3312
    /* Generate encoding of client key */
3313
3.44k
    encoded_pt_len = EVP_PKEY_get1_encoded_public_key(ckey, &encodedPoint);
3314
3315
3.44k
    if (encoded_pt_len == 0) {
3316
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EC_LIB);
3317
0
        goto err;
3318
0
    }
3319
3320
3.44k
    if (!WPACKET_sub_memcpy_u8(pkt, encodedPoint, encoded_pt_len)) {
3321
617
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3322
617
        goto err;
3323
617
    }
3324
3325
2.82k
    ret = 1;
3326
3.85k
 err:
3327
3.85k
    OPENSSL_free(encodedPoint);
3328
3.85k
    EVP_PKEY_free(ckey);
3329
3.85k
    return ret;
3330
2.82k
}
3331
3332
static int tls_construct_cke_gost(SSL_CONNECTION *s, WPACKET *pkt)
3333
0
{
3334
0
#ifndef OPENSSL_NO_GOST
3335
    /* GOST key exchange message creation */
3336
0
    EVP_PKEY_CTX *pkey_ctx = NULL;
3337
0
    EVP_PKEY *pkey = NULL;
3338
0
    size_t msglen;
3339
0
    unsigned int md_len;
3340
0
    unsigned char shared_ukm[32], tmp[256];
3341
0
    EVP_MD_CTX *ukm_hash = NULL;
3342
0
    int dgst_nid = NID_id_GostR3411_94;
3343
0
    unsigned char *pms = NULL;
3344
0
    size_t pmslen = 0;
3345
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3346
3347
0
    if ((s->s3.tmp.new_cipher->algorithm_auth & SSL_aGOST12) != 0)
3348
0
        dgst_nid = NID_id_GostR3411_2012_256;
3349
3350
    /*
3351
     * Get server certificate PKEY and create ctx from it
3352
     */
3353
0
    if ((pkey = tls_get_peer_pkey(s)) == NULL) {
3354
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3355
0
                 SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
3356
0
        return 0;
3357
0
    }
3358
3359
0
    pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,
3360
0
                                          pkey,
3361
0
                                          sctx->propq);
3362
0
    if (pkey_ctx == NULL) {
3363
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3364
0
        return 0;
3365
0
    }
3366
    /*
3367
     * If we have send a certificate, and certificate key
3368
     * parameters match those of server certificate, use
3369
     * certificate key for key exchange
3370
     */
3371
3372
    /* Otherwise, generate ephemeral key pair */
3373
0
    pmslen = 32;
3374
0
    pms = OPENSSL_malloc(pmslen);
3375
0
    if (pms == NULL) {
3376
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3377
0
        goto err;
3378
0
    }
3379
3380
0
    if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0
3381
        /* Generate session key
3382
         */
3383
0
        || RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {
3384
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3385
0
        goto err;
3386
0
    };
3387
    /*
3388
     * Compute shared IV and store it in algorithm-specific context
3389
     * data
3390
     */
3391
0
    ukm_hash = EVP_MD_CTX_new();
3392
0
    if (ukm_hash == NULL
3393
0
        || EVP_DigestInit(ukm_hash, EVP_get_digestbynid(dgst_nid)) <= 0
3394
0
        || EVP_DigestUpdate(ukm_hash, s->s3.client_random,
3395
0
                            SSL3_RANDOM_SIZE) <= 0
3396
0
        || EVP_DigestUpdate(ukm_hash, s->s3.server_random,
3397
0
                            SSL3_RANDOM_SIZE) <= 0
3398
0
        || EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len) <= 0) {
3399
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3400
0
        goto err;
3401
0
    }
3402
0
    EVP_MD_CTX_free(ukm_hash);
3403
0
    ukm_hash = NULL;
3404
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
3405
0
                          EVP_PKEY_CTRL_SET_IV, 8, shared_ukm) <= 0) {
3406
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3407
0
        goto err;
3408
0
    }
3409
    /* Make GOST keytransport blob message */
3410
    /*
3411
     * Encapsulate it into sequence
3412
     */
3413
0
    msglen = 255;
3414
0
    if (EVP_PKEY_encrypt(pkey_ctx, tmp, &msglen, pms, pmslen) <= 0) {
3415
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3416
0
        goto err;
3417
0
    }
3418
3419
0
    if (!WPACKET_put_bytes_u8(pkt, V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED)
3420
0
            || (msglen >= 0x80 && !WPACKET_put_bytes_u8(pkt, 0x81))
3421
0
            || !WPACKET_sub_memcpy_u8(pkt, tmp, msglen)) {
3422
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3423
0
        goto err;
3424
0
    }
3425
3426
0
    EVP_PKEY_CTX_free(pkey_ctx);
3427
0
    s->s3.tmp.pms = pms;
3428
0
    s->s3.tmp.pmslen = pmslen;
3429
3430
0
    return 1;
3431
0
 err:
3432
0
    EVP_PKEY_CTX_free(pkey_ctx);
3433
0
    OPENSSL_clear_free(pms, pmslen);
3434
0
    EVP_MD_CTX_free(ukm_hash);
3435
0
    return 0;
3436
#else
3437
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3438
    return 0;
3439
#endif
3440
0
}
3441
3442
#ifndef OPENSSL_NO_GOST
3443
int ossl_gost18_cke_cipher_nid(const SSL_CONNECTION *s)
3444
0
{
3445
0
    if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_MAGMA) != 0)
3446
0
        return NID_magma_ctr;
3447
0
    else if ((s->s3.tmp.new_cipher->algorithm_enc & SSL_KUZNYECHIK) != 0)
3448
0
        return NID_kuznyechik_ctr;
3449
3450
0
    return NID_undef;
3451
0
}
3452
3453
int ossl_gost_ukm(const SSL_CONNECTION *s, unsigned char *dgst_buf)
3454
0
{
3455
0
    EVP_MD_CTX *hash = NULL;
3456
0
    unsigned int md_len;
3457
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3458
0
    const EVP_MD *md = ssl_evp_md_fetch(sctx->libctx, NID_id_GostR3411_2012_256,
3459
0
                                        sctx->propq);
3460
3461
0
    if (md == NULL)
3462
0
        return 0;
3463
3464
0
    if ((hash = EVP_MD_CTX_new()) == NULL
3465
0
        || EVP_DigestInit(hash, md) <= 0
3466
0
        || EVP_DigestUpdate(hash, s->s3.client_random, SSL3_RANDOM_SIZE) <= 0
3467
0
        || EVP_DigestUpdate(hash, s->s3.server_random, SSL3_RANDOM_SIZE) <= 0
3468
0
        || EVP_DigestFinal_ex(hash, dgst_buf, &md_len) <= 0) {
3469
0
        EVP_MD_CTX_free(hash);
3470
0
        ssl_evp_md_free(md);
3471
0
        return 0;
3472
0
    }
3473
3474
0
    EVP_MD_CTX_free(hash);
3475
0
    ssl_evp_md_free(md);
3476
0
    return 1;
3477
0
}
3478
#endif
3479
3480
static int tls_construct_cke_gost18(SSL_CONNECTION *s, WPACKET *pkt)
3481
0
{
3482
0
#ifndef OPENSSL_NO_GOST
3483
    /* GOST 2018 key exchange message creation */
3484
0
    unsigned char rnd_dgst[32];
3485
0
    unsigned char *encdata = NULL;
3486
0
    EVP_PKEY_CTX *pkey_ctx = NULL;
3487
0
    EVP_PKEY *pkey;
3488
0
    unsigned char *pms = NULL;
3489
0
    size_t pmslen = 0;
3490
0
    size_t msglen;
3491
0
    int cipher_nid = ossl_gost18_cke_cipher_nid(s);
3492
0
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
3493
3494
0
    if (cipher_nid == NID_undef) {
3495
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3496
0
        return 0;
3497
0
    }
3498
3499
0
    if (ossl_gost_ukm(s, rnd_dgst) <= 0) {
3500
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3501
0
        goto err;
3502
0
    }
3503
3504
    /* Pre-master secret - random bytes */
3505
0
    pmslen = 32;
3506
0
    pms = OPENSSL_malloc(pmslen);
3507
0
    if (pms == NULL) {
3508
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3509
0
        goto err;
3510
0
    }
3511
3512
0
    if (RAND_bytes_ex(sctx->libctx, pms, pmslen, 0) <= 0) {
3513
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3514
0
        goto err;
3515
0
    }
3516
3517
     /* Get server certificate PKEY and create ctx from it */
3518
0
    if ((pkey = tls_get_peer_pkey(s)) == NULL) {
3519
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3520
0
                 SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
3521
0
        goto err;
3522
0
    }
3523
3524
0
    pkey_ctx = EVP_PKEY_CTX_new_from_pkey(sctx->libctx,
3525
0
                                          pkey,
3526
0
                                          sctx->propq);
3527
0
    if (pkey_ctx == NULL) {
3528
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3529
0
        goto err;
3530
0
    }
3531
3532
0
    if (EVP_PKEY_encrypt_init(pkey_ctx) <= 0) {
3533
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3534
0
        goto err;
3535
0
    };
3536
3537
    /* Reuse EVP_PKEY_CTRL_SET_IV, make choice in engine code */
3538
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
3539
0
                          EVP_PKEY_CTRL_SET_IV, 32, rnd_dgst) <= 0) {
3540
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3541
0
        goto err;
3542
0
    }
3543
3544
0
    if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, EVP_PKEY_OP_ENCRYPT,
3545
0
                          EVP_PKEY_CTRL_CIPHER, cipher_nid, NULL) <= 0) {
3546
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
3547
0
        goto err;
3548
0
    }
3549
3550
0
    if (EVP_PKEY_encrypt(pkey_ctx, NULL, &msglen, pms, pmslen) <= 0) {
3551
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3552
0
        goto err;
3553
0
    }
3554
3555
0
    if (!WPACKET_allocate_bytes(pkt, msglen, &encdata)
3556
0
            || EVP_PKEY_encrypt(pkey_ctx, encdata, &msglen, pms, pmslen) <= 0) {
3557
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
3558
0
        goto err;
3559
0
    }
3560
3561
0
    EVP_PKEY_CTX_free(pkey_ctx);
3562
0
    pkey_ctx = NULL;
3563
0
    s->s3.tmp.pms = pms;
3564
0
    s->s3.tmp.pmslen = pmslen;
3565
3566
0
    return 1;
3567
0
 err:
3568
0
    EVP_PKEY_CTX_free(pkey_ctx);
3569
0
    OPENSSL_clear_free(pms, pmslen);
3570
0
    return 0;
3571
#else
3572
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3573
    return 0;
3574
#endif
3575
0
}
3576
3577
static int tls_construct_cke_srp(SSL_CONNECTION *s, WPACKET *pkt)
3578
0
{
3579
0
#ifndef OPENSSL_NO_SRP
3580
0
    unsigned char *abytes = NULL;
3581
3582
0
    if (s->srp_ctx.A == NULL
3583
0
            || !WPACKET_sub_allocate_bytes_u16(pkt, BN_num_bytes(s->srp_ctx.A),
3584
0
                                               &abytes)) {
3585
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3586
0
        return 0;
3587
0
    }
3588
0
    BN_bn2bin(s->srp_ctx.A, abytes);
3589
3590
0
    OPENSSL_free(s->session->srp_username);
3591
0
    s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3592
0
    if (s->session->srp_username == NULL) {
3593
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
3594
0
        return 0;
3595
0
    }
3596
3597
0
    return 1;
3598
#else
3599
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3600
    return 0;
3601
#endif
3602
0
}
3603
3604
CON_FUNC_RETURN tls_construct_client_key_exchange(SSL_CONNECTION *s,
3605
                                                  WPACKET *pkt)
3606
13.5k
{
3607
13.5k
    unsigned long alg_k;
3608
3609
13.5k
    alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
3610
3611
    /*
3612
     * All of the construct functions below call SSLfatal() if necessary so
3613
     * no need to do so here.
3614
     */
3615
13.5k
    if ((alg_k & SSL_PSK)
3616
0
        && !tls_construct_cke_psk_preamble(s, pkt))
3617
0
        goto err;
3618
3619
13.5k
    if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3620
5.41k
        if (!tls_construct_cke_rsa(s, pkt))
3621
664
            goto err;
3622
8.16k
    } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3623
4.31k
        if (!tls_construct_cke_dhe(s, pkt))
3624
0
            goto err;
3625
4.31k
    } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3626
3.85k
        if (!tls_construct_cke_ecdhe(s, pkt))
3627
1.02k
            goto err;
3628
3.85k
    } else if (alg_k & SSL_kGOST) {
3629
0
        if (!tls_construct_cke_gost(s, pkt))
3630
0
            goto err;
3631
0
    } else if (alg_k & SSL_kGOST18) {
3632
0
        if (!tls_construct_cke_gost18(s, pkt))
3633
0
            goto err;
3634
0
    } else if (alg_k & SSL_kSRP) {
3635
0
        if (!tls_construct_cke_srp(s, pkt))
3636
0
            goto err;
3637
0
    } else if (!(alg_k & SSL_kPSK)) {
3638
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3639
0
        goto err;
3640
0
    }
3641
3642
11.8k
    return CON_FUNC_SUCCESS;
3643
1.69k
 err:
3644
1.69k
    OPENSSL_clear_free(s->s3.tmp.pms, s->s3.tmp.pmslen);
3645
1.69k
    s->s3.tmp.pms = NULL;
3646
1.69k
    s->s3.tmp.pmslen = 0;
3647
1.69k
#ifndef OPENSSL_NO_PSK
3648
1.69k
    OPENSSL_clear_free(s->s3.tmp.psk, s->s3.tmp.psklen);
3649
1.69k
    s->s3.tmp.psk = NULL;
3650
1.69k
    s->s3.tmp.psklen = 0;
3651
1.69k
#endif
3652
1.69k
    return CON_FUNC_ERROR;
3653
13.5k
}
3654
3655
int tls_client_key_exchange_post_work(SSL_CONNECTION *s)
3656
11.8k
{
3657
11.8k
    unsigned char *pms = NULL;
3658
11.8k
    size_t pmslen = 0;
3659
3660
11.8k
    pms = s->s3.tmp.pms;
3661
11.8k
    pmslen = s->s3.tmp.pmslen;
3662
3663
11.8k
#ifndef OPENSSL_NO_SRP
3664
    /* Check for SRP */
3665
11.8k
    if (s->s3.tmp.new_cipher->algorithm_mkey & SSL_kSRP) {
3666
0
        if (!srp_generate_client_master_secret(s)) {
3667
            /* SSLfatal() already called */
3668
0
            goto err;
3669
0
        }
3670
0
        return 1;
3671
0
    }
3672
11.8k
#endif
3673
3674
11.8k
    if (pms == NULL && !(s->s3.tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
3675
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_PASSED_INVALID_ARGUMENT);
3676
0
        goto err;
3677
0
    }
3678
11.8k
    if (!ssl_generate_master_secret(s, pms, pmslen, 1)) {
3679
        /* SSLfatal() already called */
3680
        /* ssl_generate_master_secret frees the pms even on error */
3681
0
        pms = NULL;
3682
0
        pmslen = 0;
3683
0
        goto err;
3684
0
    }
3685
11.8k
    pms = NULL;
3686
11.8k
    pmslen = 0;
3687
3688
#ifndef OPENSSL_NO_SCTP
3689
    if (SSL_CONNECTION_IS_DTLS(s)) {
3690
        unsigned char sctpauthkey[64];
3691
        char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3692
        size_t labellen;
3693
        SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3694
3695
        /*
3696
         * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3697
         * used.
3698
         */
3699
        memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3700
               sizeof(DTLS1_SCTP_AUTH_LABEL));
3701
3702
        /* Don't include the terminating zero. */
3703
        labellen = sizeof(labelbuffer) - 1;
3704
        if (s->mode & SSL_MODE_DTLS_SCTP_LABEL_LENGTH_BUG)
3705
            labellen += 1;
3706
3707
        if (SSL_export_keying_material(ssl, sctpauthkey,
3708
                                       sizeof(sctpauthkey), labelbuffer,
3709
                                       labellen, NULL, 0, 0) <= 0) {
3710
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3711
            goto err;
3712
        }
3713
3714
        BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3715
                 sizeof(sctpauthkey), sctpauthkey);
3716
    }
3717
#endif
3718
3719
11.8k
    return 1;
3720
0
 err:
3721
0
    OPENSSL_clear_free(pms, pmslen);
3722
0
    s->s3.tmp.pms = NULL;
3723
0
    s->s3.tmp.pmslen = 0;
3724
0
    return 0;
3725
11.8k
}
3726
3727
/*
3728
 * Check a certificate can be used for client authentication. Currently check
3729
 * cert exists, if we have a suitable digest for TLS 1.2 if static DH client
3730
 * certificates can be used and optionally checks suitability for Suite B.
3731
 */
3732
static int ssl3_check_client_certificate(SSL_CONNECTION *s)
3733
52
{
3734
    /* If no suitable signature algorithm can't use certificate */
3735
52
    if (!tls_choose_sigalg(s, 0) || s->s3.tmp.sigalg == NULL)
3736
52
        return 0;
3737
    /*
3738
     * If strict mode check suitability of chain before using it. This also
3739
     * adjusts suite B digest if necessary.
3740
     */
3741
0
    if (s->cert->cert_flags & SSL_CERT_FLAGS_CHECK_TLS_STRICT &&
3742
0
        !tls1_check_chain(s, NULL, NULL, NULL, -2))
3743
0
        return 0;
3744
0
    return 1;
3745
0
}
3746
3747
WORK_STATE tls_prepare_client_certificate(SSL_CONNECTION *s, WORK_STATE wst)
3748
44
{
3749
44
    X509 *x509 = NULL;
3750
44
    EVP_PKEY *pkey = NULL;
3751
44
    int i;
3752
44
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3753
3754
44
    if (wst == WORK_MORE_A) {
3755
        /* Let cert callback update client certificates if required */
3756
44
        if (s->cert->cert_cb) {
3757
0
            i = s->cert->cert_cb(ssl, s->cert->cert_cb_arg);
3758
0
            if (i < 0) {
3759
0
                s->rwstate = SSL_X509_LOOKUP;
3760
0
                return WORK_MORE_A;
3761
0
            }
3762
0
            if (i == 0) {
3763
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_CALLBACK_FAILED);
3764
0
                return WORK_ERROR;
3765
0
            }
3766
0
            s->rwstate = SSL_NOTHING;
3767
0
        }
3768
44
        if (ssl3_check_client_certificate(s)) {
3769
0
            if (s->post_handshake_auth == SSL_PHA_REQUESTED) {
3770
0
                return WORK_FINISHED_STOP;
3771
0
            }
3772
0
            return WORK_FINISHED_CONTINUE;
3773
0
        }
3774
3775
        /* Fall through to WORK_MORE_B */
3776
44
        wst = WORK_MORE_B;
3777
44
    }
3778
3779
    /* We need to get a client cert */
3780
44
    if (wst == WORK_MORE_B) {
3781
        /*
3782
         * If we get an error, we need to ssl->rwstate=SSL_X509_LOOKUP;
3783
         * return(-1); We then get retied later
3784
         */
3785
44
        i = ssl_do_client_cert_cb(s, &x509, &pkey);
3786
44
        if (i < 0) {
3787
0
            s->rwstate = SSL_X509_LOOKUP;
3788
0
            return WORK_MORE_B;
3789
0
        }
3790
44
        s->rwstate = SSL_NOTHING;
3791
44
        if ((i == 1) && (pkey != NULL) && (x509 != NULL)) {
3792
0
            if (!SSL_use_certificate(ssl, x509)
3793
0
                || !SSL_use_PrivateKey(ssl, pkey))
3794
0
                i = 0;
3795
44
        } else if (i == 1) {
3796
0
            i = 0;
3797
0
            ERR_raise(ERR_LIB_SSL, SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
3798
0
        }
3799
3800
44
        X509_free(x509);
3801
44
        EVP_PKEY_free(pkey);
3802
44
        if (i && !ssl3_check_client_certificate(s))
3803
0
            i = 0;
3804
44
        if (i == 0) {
3805
44
            if (s->version == SSL3_VERSION) {
3806
0
                s->s3.tmp.cert_req = 0;
3807
0
                ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_CERTIFICATE);
3808
0
                return WORK_FINISHED_CONTINUE;
3809
44
            } else {
3810
44
                s->s3.tmp.cert_req = 2;
3811
44
                s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
3812
44
                if (!ssl3_digest_cached_records(s, 0)) {
3813
                    /* SSLfatal() already called */
3814
0
                    return WORK_ERROR;
3815
0
                }
3816
44
            }
3817
44
        }
3818
3819
44
        if (!SSL_CONNECTION_IS_TLS13(s)
3820
0
                || (s->options & SSL_OP_NO_TX_CERTIFICATE_COMPRESSION) != 0)
3821
44
            s->ext.compress_certificate_from_peer[0] = TLSEXT_comp_cert_none;
3822
3823
44
        if (s->post_handshake_auth == SSL_PHA_REQUESTED)
3824
0
            return WORK_FINISHED_STOP;
3825
44
        return WORK_FINISHED_CONTINUE;
3826
44
    }
3827
3828
    /* Shouldn't ever get here */
3829
44
    SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3830
0
    return WORK_ERROR;
3831
44
}
3832
3833
CON_FUNC_RETURN tls_construct_client_certificate(SSL_CONNECTION *s,
3834
                                                 WPACKET *pkt)
3835
15
{
3836
15
    CERT_PKEY *cpk = NULL;
3837
15
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
3838
3839
15
    if (SSL_CONNECTION_IS_TLS13(s)) {
3840
0
        if (s->pha_context == NULL) {
3841
            /* no context available, add 0-length context */
3842
0
            if (!WPACKET_put_bytes_u8(pkt, 0)) {
3843
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3844
0
                return CON_FUNC_ERROR;
3845
0
            }
3846
0
        } else if (!WPACKET_sub_memcpy_u8(pkt, s->pha_context, s->pha_context_len)) {
3847
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3848
0
            return CON_FUNC_ERROR;
3849
0
        }
3850
0
    }
3851
15
    if (s->s3.tmp.cert_req != 2)
3852
0
        cpk = s->cert->key;
3853
15
    switch (s->ext.client_cert_type) {
3854
0
    case TLSEXT_cert_type_rpk:
3855
0
        if (!tls_output_rpk(s, pkt, cpk)) {
3856
            /* SSLfatal() already called */
3857
0
            return CON_FUNC_ERROR;
3858
0
        }
3859
0
        break;
3860
15
    case TLSEXT_cert_type_x509:
3861
15
        if (!ssl3_output_cert_chain(s, pkt, cpk, 0)) {
3862
            /* SSLfatal() already called */
3863
0
            return CON_FUNC_ERROR;
3864
0
        }
3865
15
        break;
3866
15
    default:
3867
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3868
0
        return CON_FUNC_ERROR;
3869
15
    }
3870
3871
    /*
3872
     * If we attempted to write early data or we're in middlebox compat mode
3873
     * then we deferred changing the handshake write keys to the last possible
3874
     * moment. We need to do it now.
3875
     */
3876
15
    if (SSL_CONNECTION_IS_TLS13(s)
3877
0
            && !SSL_IS_QUIC_HANDSHAKE(s)
3878
0
            && SSL_IS_FIRST_HANDSHAKE(s)
3879
0
            && (s->early_data_state != SSL_EARLY_DATA_NONE
3880
0
                || (s->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
3881
0
            && (!ssl->method->ssl3_enc->change_cipher_state(s,
3882
0
                    SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
3883
        /*
3884
         * This is a fatal error, which leaves enc_write_ctx in an inconsistent
3885
         * state and thus ssl3_send_alert may crash.
3886
         */
3887
0
        SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);
3888
0
        return CON_FUNC_ERROR;
3889
0
    }
3890
3891
15
    return CON_FUNC_SUCCESS;
3892
15
}
3893
3894
#ifndef OPENSSL_NO_COMP_ALG
3895
CON_FUNC_RETURN tls_construct_client_compressed_certificate(SSL_CONNECTION *sc,
3896
                                                            WPACKET *pkt)
3897
{
3898
    SSL *ssl = SSL_CONNECTION_GET_SSL(sc);
3899
    WPACKET tmppkt;
3900
    BUF_MEM *buf = NULL;
3901
    size_t length;
3902
    size_t max_length;
3903
    COMP_METHOD *method;
3904
    COMP_CTX *comp = NULL;
3905
    int comp_len;
3906
    int ret = 0;
3907
    int alg = sc->ext.compress_certificate_from_peer[0];
3908
3909
    /* Note that sc->s3.tmp.cert_req == 2 is checked in write transition */
3910
3911
    if ((buf = BUF_MEM_new()) == NULL || !WPACKET_init(&tmppkt, buf))
3912
        goto err;
3913
3914
    /* Use the |tmppkt| for the to-be-compressed data */
3915
    if (sc->pha_context == NULL) {
3916
        /* no context available, add 0-length context */
3917
        if (!WPACKET_put_bytes_u8(&tmppkt, 0))
3918
            goto err;
3919
    } else if (!WPACKET_sub_memcpy_u8(&tmppkt, sc->pha_context, sc->pha_context_len))
3920
        goto err;
3921
3922
    if (!ssl3_output_cert_chain(sc, &tmppkt, sc->cert->key, 0)) {
3923
        /* SSLfatal() already called */
3924
        goto out;
3925
    }
3926
3927
    /* continue with the real |pkt| */
3928
    if (!WPACKET_put_bytes_u16(pkt, alg)
3929
            || !WPACKET_get_total_written(&tmppkt, &length)
3930
            || !WPACKET_put_bytes_u24(pkt, length))
3931
        goto err;
3932
3933
    switch (alg) {
3934
    case TLSEXT_comp_cert_zlib:
3935
        method = COMP_zlib_oneshot();
3936
        break;
3937
    case TLSEXT_comp_cert_brotli:
3938
        method = COMP_brotli_oneshot();
3939
        break;
3940
    case TLSEXT_comp_cert_zstd:
3941
        method = COMP_zstd_oneshot();
3942
        break;
3943
    default:
3944
        goto err;
3945
    }
3946
    max_length = ossl_calculate_comp_expansion(alg, length);
3947
3948
    if ((comp = COMP_CTX_new(method)) == NULL
3949
            || !WPACKET_start_sub_packet_u24(pkt)
3950
            || !WPACKET_reserve_bytes(pkt, max_length, NULL))
3951
        goto err;
3952
3953
    comp_len = COMP_compress_block(comp, WPACKET_get_curr(pkt), (int)max_length,
3954
                                   (unsigned char *)buf->data, (int)length);
3955
    if (comp_len <= 0)
3956
        goto err;
3957
3958
    if (!WPACKET_allocate_bytes(pkt, comp_len, NULL)
3959
            || !WPACKET_close(pkt))
3960
        goto err;
3961
3962
    /*
3963
     * If we attempted to write early data or we're in middlebox compat mode
3964
     * then we deferred changing the handshake write keys to the last possible
3965
     * moment. We need to do it now.
3966
     */
3967
    if (SSL_IS_FIRST_HANDSHAKE(sc)
3968
            && !SSL_IS_QUIC_HANDSHAKE(sc)
3969
            && (sc->early_data_state != SSL_EARLY_DATA_NONE
3970
                || (sc->options & SSL_OP_ENABLE_MIDDLEBOX_COMPAT) != 0)
3971
            && (!ssl->method->ssl3_enc->change_cipher_state(sc,
3972
                    SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_CLIENT_WRITE))) {
3973
        /*
3974
         * This is a fatal error, which leaves sc->enc_write_ctx in an
3975
         * inconsistent state and thus ssl3_send_alert may crash.
3976
         */
3977
        SSLfatal(sc, SSL_AD_NO_ALERT, SSL_R_CANNOT_CHANGE_CIPHER);
3978
        goto out;
3979
    }
3980
    ret = 1;
3981
    goto out;
3982
3983
 err:
3984
    SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
3985
 out:
3986
    if (buf != NULL) {
3987
        /* If |buf| is NULL, then |tmppkt| could not have been initialized */
3988
        WPACKET_cleanup(&tmppkt);
3989
    }
3990
    BUF_MEM_free(buf);
3991
    COMP_CTX_free(comp);
3992
    return ret;
3993
}
3994
#endif
3995
3996
int ssl3_check_cert_and_algorithm(SSL_CONNECTION *s)
3997
25.6k
{
3998
25.6k
    const SSL_CERT_LOOKUP *clu;
3999
25.6k
    size_t idx;
4000
25.6k
    long alg_k, alg_a;
4001
25.6k
    EVP_PKEY *pkey;
4002
4003
25.6k
    alg_k = s->s3.tmp.new_cipher->algorithm_mkey;
4004
25.6k
    alg_a = s->s3.tmp.new_cipher->algorithm_auth;
4005
4006
    /* we don't have a certificate */
4007
25.6k
    if (!(alg_a & SSL_aCERT))
4008
20.4k
        return 1;
4009
4010
    /* This is the passed certificate */
4011
5.19k
    pkey = tls_get_peer_pkey(s);
4012
5.19k
    clu = ssl_cert_lookup_by_pkey(pkey, &idx, SSL_CONNECTION_GET_CTX(s));
4013
4014
    /* Check certificate is recognised and suitable for cipher */
4015
5.19k
    if (clu == NULL || (alg_a & clu->amask) == 0) {
4016
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_MISSING_SIGNING_CERT);
4017
0
        return 0;
4018
0
    }
4019
4020
5.19k
    if (alg_k & (SSL_kRSA | SSL_kRSAPSK) && idx != SSL_PKEY_RSA) {
4021
10
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
4022
10
                 SSL_R_MISSING_RSA_ENCRYPTING_CERT);
4023
10
        return 0;
4024
10
    }
4025
4026
5.18k
    if ((alg_k & SSL_kDHE) && (s->s3.peer_tmp == NULL)) {
4027
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4028
0
        return 0;
4029
0
    }
4030
4031
    /* Early out to skip the checks below */
4032
5.18k
    if (s->session->peer_rpk != NULL)
4033
0
        return 1;
4034
4035
5.18k
    if (clu->amask & SSL_aECDSA) {
4036
0
        if (ssl_check_srvr_ecc_cert_and_alg(s->session->peer, s))
4037
0
            return 1;
4038
0
        SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_BAD_ECC_CERT);
4039
0
        return 0;
4040
0
    }
4041
4042
5.18k
    return 1;
4043
5.18k
}
4044
4045
#ifndef OPENSSL_NO_NEXTPROTONEG
4046
CON_FUNC_RETURN tls_construct_next_proto(SSL_CONNECTION *s, WPACKET *pkt)
4047
0
{
4048
0
    size_t len, padding_len;
4049
0
    unsigned char *padding = NULL;
4050
4051
0
    len = s->ext.npn_len;
4052
0
    padding_len = 32 - ((len + 2) % 32);
4053
4054
0
    if (!WPACKET_sub_memcpy_u8(pkt, s->ext.npn, len)
4055
0
            || !WPACKET_sub_allocate_bytes_u8(pkt, padding_len, &padding)) {
4056
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4057
0
        return CON_FUNC_ERROR;
4058
0
    }
4059
4060
0
    memset(padding, 0, padding_len);
4061
4062
0
    return CON_FUNC_SUCCESS;
4063
0
}
4064
#endif
4065
4066
MSG_PROCESS_RETURN tls_process_hello_req(SSL_CONNECTION *s, PACKET *pkt)
4067
1.35k
{
4068
1.35k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
4069
4070
1.35k
    if (PACKET_remaining(pkt) > 0) {
4071
        /* should contain no data */
4072
0
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4073
0
        return MSG_PROCESS_ERROR;
4074
0
    }
4075
4076
1.35k
    if ((s->options & SSL_OP_NO_RENEGOTIATION)) {
4077
0
        ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
4078
0
        return MSG_PROCESS_FINISHED_READING;
4079
0
    }
4080
4081
    /*
4082
     * This is a historical discrepancy (not in the RFC) maintained for
4083
     * compatibility reasons. If a TLS client receives a HelloRequest it will
4084
     * attempt an abbreviated handshake. However if a DTLS client receives a
4085
     * HelloRequest it will do a full handshake. Either behaviour is reasonable
4086
     * but doing one for TLS and another for DTLS is odd.
4087
     */
4088
1.35k
    if (SSL_CONNECTION_IS_DTLS(s))
4089
0
        SSL_renegotiate(ssl);
4090
1.35k
    else
4091
1.35k
        SSL_renegotiate_abbreviated(ssl);
4092
4093
1.35k
    return MSG_PROCESS_FINISHED_READING;
4094
1.35k
}
4095
4096
static MSG_PROCESS_RETURN tls_process_encrypted_extensions(SSL_CONNECTION *s,
4097
                                                           PACKET *pkt)
4098
23.2k
{
4099
23.2k
    PACKET extensions;
4100
23.2k
    RAW_EXTENSION *rawexts = NULL;
4101
4102
23.2k
    if (!PACKET_as_length_prefixed_2(pkt, &extensions)
4103
23.1k
            || PACKET_remaining(pkt) != 0) {
4104
117
        SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_R_LENGTH_MISMATCH);
4105
117
        goto err;
4106
117
    }
4107
4108
23.1k
    if (!tls_collect_extensions(s, &extensions,
4109
23.1k
                                SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS, &rawexts,
4110
23.1k
                                NULL, 1)
4111
23.0k
            || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
4112
23.0k
                                         rawexts, NULL, 0, 1)) {
4113
        /* SSLfatal() already called */
4114
1.23k
        goto err;
4115
1.23k
    }
4116
4117
21.8k
    OPENSSL_free(rawexts);
4118
21.8k
    return MSG_PROCESS_CONTINUE_READING;
4119
4120
1.35k
 err:
4121
1.35k
    OPENSSL_free(rawexts);
4122
1.35k
    return MSG_PROCESS_ERROR;
4123
23.1k
}
4124
4125
int ssl_do_client_cert_cb(SSL_CONNECTION *s, X509 **px509, EVP_PKEY **ppkey)
4126
52
{
4127
52
    int i = 0;
4128
52
    SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
4129
4130
52
#ifndef OPENSSL_NO_ENGINE
4131
52
    if (sctx->client_cert_engine) {
4132
0
        i = tls_engine_load_ssl_client_cert(s, px509, ppkey);
4133
0
        if (i != 0)
4134
0
            return i;
4135
0
    }
4136
52
#endif
4137
52
    if (sctx->client_cert_cb)
4138
0
        i = sctx->client_cert_cb(SSL_CONNECTION_GET_USER_SSL(s), px509, ppkey);
4139
52
    return i;
4140
52
}
4141
4142
int ssl_cipher_list_to_bytes(SSL_CONNECTION *s, STACK_OF(SSL_CIPHER) *sk,
4143
                             WPACKET *pkt)
4144
75.6k
{
4145
75.6k
    int i;
4146
75.6k
    size_t totlen = 0, len, maxlen, maxverok = 0;
4147
75.6k
    int empty_reneg_info_scsv = !s->renegotiate
4148
74.6k
                                && !SSL_CONNECTION_IS_DTLS(s)
4149
57.1k
                                && ssl_security(s, SSL_SECOP_VERSION, 0, TLS1_VERSION, NULL)
4150
23.3k
                                && s->min_proto_version <= TLS1_VERSION;
4151
75.6k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
4152
4153
    /* Set disabled masks for this session */
4154
75.6k
    if (!ssl_set_client_disabled(s)) {
4155
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_PROTOCOLS_AVAILABLE);
4156
0
        return 0;
4157
0
    }
4158
4159
75.6k
    if (sk == NULL) {
4160
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4161
0
        return 0;
4162
0
    }
4163
4164
#ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
4165
# if OPENSSL_MAX_TLS1_2_CIPHER_LENGTH < 6
4166
#  error Max cipher length too short
4167
# endif
4168
    /*
4169
     * Some servers hang if client hello > 256 bytes as hack workaround
4170
     * chop number of supported ciphers to keep it well below this if we
4171
     * use TLS v1.2
4172
     */
4173
    if (TLS1_get_version(ssl) >= TLS1_2_VERSION)
4174
        maxlen = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
4175
    else
4176
#endif
4177
        /* Maximum length that can be stored in 2 bytes. Length must be even */
4178
75.6k
        maxlen = 0xfffe;
4179
4180
75.6k
    if (empty_reneg_info_scsv)
4181
23.3k
        maxlen -= 2;
4182
75.6k
    if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV)
4183
0
        maxlen -= 2;
4184
4185
7.36M
    for (i = 0; i < sk_SSL_CIPHER_num(sk) && totlen < maxlen; i++) {
4186
7.28M
        const SSL_CIPHER *c;
4187
4188
7.28M
        c = sk_SSL_CIPHER_value(sk, i);
4189
        /* Skip disabled ciphers */
4190
7.28M
        if (ssl_cipher_disabled(s, c, SSL_SECOP_CIPHER_SUPPORTED, 0))
4191
3.14M
            continue;
4192
4193
4.13M
        if (!ssl->method->put_cipher_by_char(c, pkt, &len)) {
4194
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4195
0
            return 0;
4196
0
        }
4197
4198
        /* Sanity check that the maximum version we offer has ciphers enabled */
4199
4.13M
        if (!maxverok) {
4200
75.6k
            int minproto = SSL_CONNECTION_IS_DTLS(s) ? c->min_dtls : c->min_tls;
4201
75.6k
            int maxproto = SSL_CONNECTION_IS_DTLS(s) ? c->max_dtls : c->max_tls;
4202
4203
75.6k
            if (ssl_version_cmp(s, maxproto, s->s3.tmp.max_ver) >= 0
4204
75.6k
                    && ssl_version_cmp(s, minproto, s->s3.tmp.max_ver) <= 0)
4205
75.6k
                maxverok = 1;
4206
75.6k
        }
4207
4208
4.13M
        totlen += len;
4209
4.13M
    }
4210
4211
75.6k
    if (totlen == 0 || !maxverok) {
4212
0
        const char *maxvertext =
4213
0
            !maxverok
4214
0
            ? "No ciphers enabled for max supported SSL/TLS version"
4215
0
            : NULL;
4216
4217
0
        SSLfatal_data(s, SSL_AD_INTERNAL_ERROR, SSL_R_NO_CIPHERS_AVAILABLE,
4218
0
                      maxvertext);
4219
0
        return 0;
4220
0
    }
4221
4222
75.6k
    if (totlen != 0) {
4223
75.6k
        if (empty_reneg_info_scsv) {
4224
23.3k
            static const SSL_CIPHER scsv = {
4225
23.3k
                0, NULL, NULL, SSL3_CK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
4226
23.3k
            };
4227
23.3k
            if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {
4228
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4229
0
                return 0;
4230
0
            }
4231
23.3k
        }
4232
75.6k
        if (s->mode & SSL_MODE_SEND_FALLBACK_SCSV) {
4233
0
            static const SSL_CIPHER scsv = {
4234
0
                0, NULL, NULL, SSL3_CK_FALLBACK_SCSV, 0, 0, 0, 0, 0, 0, 0, 0, 0
4235
0
            };
4236
0
            if (!ssl->method->put_cipher_by_char(&scsv, pkt, &len)) {
4237
0
                SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
4238
0
                return 0;
4239
0
            }
4240
0
        }
4241
75.6k
    }
4242
4243
75.6k
    return 1;
4244
75.6k
}
4245
4246
CON_FUNC_RETURN tls_construct_end_of_early_data(SSL_CONNECTION *s, WPACKET *pkt)
4247
0
{
4248
0
    if (s->early_data_state != SSL_EARLY_DATA_WRITE_RETRY
4249
0
            && s->early_data_state != SSL_EARLY_DATA_FINISHED_WRITING) {
4250
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
4251
0
        return CON_FUNC_ERROR;
4252
0
    }
4253
4254
0
    s->early_data_state = SSL_EARLY_DATA_FINISHED_WRITING;
4255
0
    return CON_FUNC_SUCCESS;
4256
0
}