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