Coverage Report

Created: 2026-03-09 06:55

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