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