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