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