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