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