Coverage Report

Created: 2023-06-08 06:43

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