Coverage Report

Created: 2023-04-12 06:22

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