Coverage Report

Created: 2025-08-28 07:07

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