Coverage Report

Created: 2026-04-12 07:08

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