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