Coverage Report

Created: 2026-11-16 07:12

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