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