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