Coverage Report

Created: 2025-12-08 06:22

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