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