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