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