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