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