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