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