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