Coverage Report

Created: 2025-08-25 06:30

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