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