Small cleanup of some build.info files
[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, 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, 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         /* Get length of the parameters we have written above */
2619         if (!WPACKET_get_length(pkt, &paramlen)) {
2620             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2621                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2622                      ERR_R_INTERNAL_ERROR);
2623             goto err;
2624         }
2625         /* send signature algorithm */
2626         if (SSL_USE_SIGALGS(s) && !WPACKET_put_bytes_u16(pkt, lu->sigalg)) {
2627             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2628                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2629                      ERR_R_INTERNAL_ERROR);
2630             goto err;
2631         }
2632         /*
2633          * Create the signature. We don't know the actual length of the sig
2634          * until after we've created it, so we reserve enough bytes for it
2635          * up front, and then properly allocate them in the WPACKET
2636          * afterwards.
2637          */
2638         siglen = EVP_PKEY_size(pkey);
2639         if (!WPACKET_sub_reserve_bytes_u16(pkt, siglen, &sigbytes1)
2640             || EVP_DigestSignInit(md_ctx, &pctx, md, NULL, pkey) <= 0) {
2641             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2642                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2643                      ERR_R_INTERNAL_ERROR);
2644             goto err;
2645         }
2646         if (lu->sig == EVP_PKEY_RSA_PSS) {
2647             if (EVP_PKEY_CTX_set_rsa_padding(pctx, RSA_PKCS1_PSS_PADDING) <= 0
2648                 || EVP_PKEY_CTX_set_rsa_pss_saltlen(pctx, RSA_PSS_SALTLEN_DIGEST) <= 0) {
2649                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2650                          SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2651                         ERR_R_EVP_LIB);
2652                 goto err;
2653             }
2654         }
2655         tbslen = construct_key_exchange_tbs(s, &tbs,
2656                                             s->init_buf->data + paramoffset,
2657                                             paramlen);
2658         if (tbslen == 0) {
2659             /* SSLfatal() already called */
2660             goto err;
2661         }
2662         rv = EVP_DigestSign(md_ctx, sigbytes1, &siglen, tbs, tbslen);
2663         OPENSSL_free(tbs);
2664         if (rv <= 0 || !WPACKET_sub_allocate_bytes_u16(pkt, siglen, &sigbytes2)
2665             || sigbytes1 != sigbytes2) {
2666             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2667                      SSL_F_TLS_CONSTRUCT_SERVER_KEY_EXCHANGE,
2668                      ERR_R_INTERNAL_ERROR);
2669             goto err;
2670         }
2671     }
2672
2673     EVP_MD_CTX_free(md_ctx);
2674     return 1;
2675  err:
2676 #ifndef OPENSSL_NO_DH
2677     EVP_PKEY_free(pkdh);
2678 #endif
2679 #ifndef OPENSSL_NO_EC
2680     OPENSSL_free(encodedPoint);
2681 #endif
2682     EVP_MD_CTX_free(md_ctx);
2683     return 0;
2684 }
2685
2686 int tls_construct_certificate_request(SSL *s, WPACKET *pkt)
2687 {
2688     if (SSL_IS_TLS13(s)) {
2689         /* TODO(TLS1.3) for now send empty request context */
2690         if (!WPACKET_put_bytes_u8(pkt, 0)) {
2691             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2692                      SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2693                      ERR_R_INTERNAL_ERROR);
2694             return 0;
2695         }
2696
2697         if (!tls_construct_extensions(s, pkt,
2698                                       SSL_EXT_TLS1_3_CERTIFICATE_REQUEST, NULL,
2699                                       0)) {
2700             /* SSLfatal() already called */
2701             return 0;
2702         }
2703         goto done;
2704     }
2705
2706     /* get the list of acceptable cert types */
2707     if (!WPACKET_start_sub_packet_u8(pkt)
2708         || !ssl3_get_req_cert_type(s, pkt) || !WPACKET_close(pkt)) {
2709         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2710                  SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2711         return 0;
2712     }
2713
2714     if (SSL_USE_SIGALGS(s)) {
2715         const uint16_t *psigs;
2716         size_t nl = tls12_get_psigalgs(s, 1, &psigs);
2717
2718         if (!WPACKET_start_sub_packet_u16(pkt)
2719                 || !WPACKET_set_flags(pkt, WPACKET_FLAGS_NON_ZERO_LENGTH)
2720                 || !tls12_copy_sigalgs(s, pkt, psigs, nl)
2721                 || !WPACKET_close(pkt)) {
2722             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2723                      SSL_F_TLS_CONSTRUCT_CERTIFICATE_REQUEST,
2724                      ERR_R_INTERNAL_ERROR);
2725             return 0;
2726         }
2727     }
2728
2729     if (!construct_ca_names(s, pkt)) {
2730         /* SSLfatal() already called */
2731         return 0;
2732     }
2733
2734  done:
2735     s->s3->tmp.cert_request = 1;
2736     return 1;
2737 }
2738
2739 static int tls_process_cke_psk_preamble(SSL *s, PACKET *pkt)
2740 {
2741 #ifndef OPENSSL_NO_PSK
2742     unsigned char psk[PSK_MAX_PSK_LEN];
2743     size_t psklen;
2744     PACKET psk_identity;
2745
2746     if (!PACKET_get_length_prefixed_2(pkt, &psk_identity)) {
2747         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2748                  SSL_R_LENGTH_MISMATCH);
2749         return 0;
2750     }
2751     if (PACKET_remaining(&psk_identity) > PSK_MAX_IDENTITY_LEN) {
2752         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2753                  SSL_R_DATA_LENGTH_TOO_LONG);
2754         return 0;
2755     }
2756     if (s->psk_server_callback == NULL) {
2757         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2758                  SSL_R_PSK_NO_SERVER_CB);
2759         return 0;
2760     }
2761
2762     if (!PACKET_strndup(&psk_identity, &s->session->psk_identity)) {
2763         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2764                  ERR_R_INTERNAL_ERROR);
2765         return 0;
2766     }
2767
2768     psklen = s->psk_server_callback(s, s->session->psk_identity,
2769                                     psk, sizeof(psk));
2770
2771     if (psklen > PSK_MAX_PSK_LEN) {
2772         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2773                  ERR_R_INTERNAL_ERROR);
2774         return 0;
2775     } else if (psklen == 0) {
2776         /*
2777          * PSK related to the given identity not found
2778          */
2779         SSLfatal(s, SSL_AD_UNKNOWN_PSK_IDENTITY,
2780                  SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2781                  SSL_R_PSK_IDENTITY_NOT_FOUND);
2782         return 0;
2783     }
2784
2785     OPENSSL_free(s->s3->tmp.psk);
2786     s->s3->tmp.psk = OPENSSL_memdup(psk, psklen);
2787     OPENSSL_cleanse(psk, psklen);
2788
2789     if (s->s3->tmp.psk == NULL) {
2790         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
2791                  SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE, ERR_R_MALLOC_FAILURE);
2792         return 0;
2793     }
2794
2795     s->s3->tmp.psklen = psklen;
2796
2797     return 1;
2798 #else
2799     /* Should never happen */
2800     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_PSK_PREAMBLE,
2801              ERR_R_INTERNAL_ERROR);
2802     return 0;
2803 #endif
2804 }
2805
2806 static int tls_process_cke_rsa(SSL *s, PACKET *pkt)
2807 {
2808 #ifndef OPENSSL_NO_RSA
2809     unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2810     int decrypt_len;
2811     unsigned char decrypt_good, version_good;
2812     size_t j, padding_len;
2813     PACKET enc_premaster;
2814     RSA *rsa = NULL;
2815     unsigned char *rsa_decrypt = NULL;
2816     int ret = 0;
2817
2818     rsa = EVP_PKEY_get0_RSA(s->cert->pkeys[SSL_PKEY_RSA].privatekey);
2819     if (rsa == NULL) {
2820         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2821                  SSL_R_MISSING_RSA_CERTIFICATE);
2822         return 0;
2823     }
2824
2825     /* SSLv3 and pre-standard DTLS omit the length bytes. */
2826     if (s->version == SSL3_VERSION || s->version == DTLS1_BAD_VER) {
2827         enc_premaster = *pkt;
2828     } else {
2829         if (!PACKET_get_length_prefixed_2(pkt, &enc_premaster)
2830             || PACKET_remaining(pkt) != 0) {
2831             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2832                      SSL_R_LENGTH_MISMATCH);
2833             return 0;
2834         }
2835     }
2836
2837     /*
2838      * We want to be sure that the plaintext buffer size makes it safe to
2839      * iterate over the entire size of a premaster secret
2840      * (SSL_MAX_MASTER_KEY_LENGTH). Reject overly short RSA keys because
2841      * their ciphertext cannot accommodate a premaster secret anyway.
2842      */
2843     if (RSA_size(rsa) < SSL_MAX_MASTER_KEY_LENGTH) {
2844         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2845                  RSA_R_KEY_SIZE_TOO_SMALL);
2846         return 0;
2847     }
2848
2849     rsa_decrypt = OPENSSL_malloc(RSA_size(rsa));
2850     if (rsa_decrypt == NULL) {
2851         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2852                  ERR_R_MALLOC_FAILURE);
2853         return 0;
2854     }
2855
2856     /*
2857      * We must not leak whether a decryption failure occurs because of
2858      * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2859      * section 7.4.7.1). The code follows that advice of the TLS RFC and
2860      * generates a random premaster secret for the case that the decrypt
2861      * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2862      */
2863
2864     if (ssl_randbytes(s, rand_premaster_secret,
2865                       sizeof(rand_premaster_secret)) <= 0) {
2866         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2867                  ERR_R_INTERNAL_ERROR);
2868         goto err;
2869     }
2870
2871     /*
2872      * Decrypt with no padding. PKCS#1 padding will be removed as part of
2873      * the timing-sensitive code below.
2874      */
2875      /* TODO(size_t): Convert this function */
2876     decrypt_len = (int)RSA_private_decrypt((int)PACKET_remaining(&enc_premaster),
2877                                            PACKET_data(&enc_premaster),
2878                                            rsa_decrypt, rsa, RSA_NO_PADDING);
2879     if (decrypt_len < 0) {
2880         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2881                  ERR_R_INTERNAL_ERROR);
2882         goto err;
2883     }
2884
2885     /* Check the padding. See RFC 3447, section 7.2.2. */
2886
2887     /*
2888      * The smallest padded premaster is 11 bytes of overhead. Small keys
2889      * are publicly invalid, so this may return immediately. This ensures
2890      * PS is at least 8 bytes.
2891      */
2892     if (decrypt_len < 11 + SSL_MAX_MASTER_KEY_LENGTH) {
2893         SSLfatal(s, SSL_AD_DECRYPT_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2894                  SSL_R_DECRYPTION_FAILED);
2895         goto err;
2896     }
2897
2898     padding_len = decrypt_len - SSL_MAX_MASTER_KEY_LENGTH;
2899     decrypt_good = constant_time_eq_int_8(rsa_decrypt[0], 0) &
2900         constant_time_eq_int_8(rsa_decrypt[1], 2);
2901     for (j = 2; j < padding_len - 1; j++) {
2902         decrypt_good &= ~constant_time_is_zero_8(rsa_decrypt[j]);
2903     }
2904     decrypt_good &= constant_time_is_zero_8(rsa_decrypt[padding_len - 1]);
2905
2906     /*
2907      * If the version in the decrypted pre-master secret is correct then
2908      * version_good will be 0xff, otherwise it'll be zero. The
2909      * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2910      * (http://eprint.iacr.org/2003/052/) exploits the version number
2911      * check as a "bad version oracle". Thus version checks are done in
2912      * constant time and are treated like any other decryption error.
2913      */
2914     version_good =
2915         constant_time_eq_8(rsa_decrypt[padding_len],
2916                            (unsigned)(s->client_version >> 8));
2917     version_good &=
2918         constant_time_eq_8(rsa_decrypt[padding_len + 1],
2919                            (unsigned)(s->client_version & 0xff));
2920
2921     /*
2922      * The premaster secret must contain the same version number as the
2923      * ClientHello to detect version rollback attacks (strangely, the
2924      * protocol does not offer such protection for DH ciphersuites).
2925      * However, buggy clients exist that send the negotiated protocol
2926      * version instead if the server does not support the requested
2927      * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2928      * clients.
2929      */
2930     if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2931         unsigned char workaround_good;
2932         workaround_good = constant_time_eq_8(rsa_decrypt[padding_len],
2933                                              (unsigned)(s->version >> 8));
2934         workaround_good &=
2935             constant_time_eq_8(rsa_decrypt[padding_len + 1],
2936                                (unsigned)(s->version & 0xff));
2937         version_good |= workaround_good;
2938     }
2939
2940     /*
2941      * Both decryption and version must be good for decrypt_good to
2942      * remain non-zero (0xff).
2943      */
2944     decrypt_good &= version_good;
2945
2946     /*
2947      * Now copy rand_premaster_secret over from p using
2948      * decrypt_good_mask. If decryption failed, then p does not
2949      * contain valid plaintext, however, a check above guarantees
2950      * it is still sufficiently large to read from.
2951      */
2952     for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2953         rsa_decrypt[padding_len + j] =
2954             constant_time_select_8(decrypt_good,
2955                                    rsa_decrypt[padding_len + j],
2956                                    rand_premaster_secret[j]);
2957     }
2958
2959     if (!ssl_generate_master_secret(s, rsa_decrypt + padding_len,
2960                                     sizeof(rand_premaster_secret), 0)) {
2961         /* SSLfatal() already called */
2962         goto err;
2963     }
2964
2965     ret = 1;
2966  err:
2967     OPENSSL_free(rsa_decrypt);
2968     return ret;
2969 #else
2970     /* Should never happen */
2971     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_RSA,
2972              ERR_R_INTERNAL_ERROR);
2973     return 0;
2974 #endif
2975 }
2976
2977 static int tls_process_cke_dhe(SSL *s, PACKET *pkt)
2978 {
2979 #ifndef OPENSSL_NO_DH
2980     EVP_PKEY *skey = NULL;
2981     DH *cdh;
2982     unsigned int i;
2983     BIGNUM *pub_key;
2984     const unsigned char *data;
2985     EVP_PKEY *ckey = NULL;
2986     int ret = 0;
2987
2988     if (!PACKET_get_net_2(pkt, &i) || PACKET_remaining(pkt) != i) {
2989         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2990                SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2991         goto err;
2992     }
2993     skey = s->s3->tmp.pkey;
2994     if (skey == NULL) {
2995         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
2996                  SSL_R_MISSING_TMP_DH_KEY);
2997         goto err;
2998     }
2999
3000     if (PACKET_remaining(pkt) == 0L) {
3001         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3002                  SSL_R_MISSING_TMP_DH_KEY);
3003         goto err;
3004     }
3005     if (!PACKET_get_bytes(pkt, &data, i)) {
3006         /* We already checked we have enough data */
3007         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3008                  ERR_R_INTERNAL_ERROR);
3009         goto err;
3010     }
3011     ckey = EVP_PKEY_new();
3012     if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) == 0) {
3013         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3014                  SSL_R_BN_LIB);
3015         goto err;
3016     }
3017     cdh = EVP_PKEY_get0_DH(ckey);
3018     pub_key = BN_bin2bn(data, i, NULL);
3019
3020     if (pub_key == NULL || !DH_set0_key(cdh, pub_key, NULL)) {
3021         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3022                  ERR_R_INTERNAL_ERROR);
3023         if (pub_key != NULL)
3024             BN_free(pub_key);
3025         goto err;
3026     }
3027
3028     if (ssl_derive(s, skey, ckey, 1) == 0) {
3029         /* SSLfatal() already called */
3030         goto err;
3031     }
3032
3033     ret = 1;
3034     EVP_PKEY_free(s->s3->tmp.pkey);
3035     s->s3->tmp.pkey = NULL;
3036  err:
3037     EVP_PKEY_free(ckey);
3038     return ret;
3039 #else
3040     /* Should never happen */
3041     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_DHE,
3042              ERR_R_INTERNAL_ERROR);
3043     return 0;
3044 #endif
3045 }
3046
3047 static int tls_process_cke_ecdhe(SSL *s, PACKET *pkt)
3048 {
3049 #ifndef OPENSSL_NO_EC
3050     EVP_PKEY *skey = s->s3->tmp.pkey;
3051     EVP_PKEY *ckey = NULL;
3052     int ret = 0;
3053
3054     if (PACKET_remaining(pkt) == 0L) {
3055         /* We don't support ECDH client auth */
3056         SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_F_TLS_PROCESS_CKE_ECDHE,
3057                  SSL_R_MISSING_TMP_ECDH_KEY);
3058         goto err;
3059     } else {
3060         unsigned int i;
3061         const unsigned char *data;
3062
3063         /*
3064          * Get client's public key from encoded point in the
3065          * ClientKeyExchange message.
3066          */
3067
3068         /* Get encoded point length */
3069         if (!PACKET_get_1(pkt, &i) || !PACKET_get_bytes(pkt, &data, i)
3070             || PACKET_remaining(pkt) != 0) {
3071             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3072                      SSL_R_LENGTH_MISMATCH);
3073             goto err;
3074         }
3075         ckey = EVP_PKEY_new();
3076         if (ckey == NULL || EVP_PKEY_copy_parameters(ckey, skey) <= 0) {
3077             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3078                      ERR_R_EVP_LIB);
3079             goto err;
3080         }
3081         if (EVP_PKEY_set1_tls_encodedpoint(ckey, data, i) == 0) {
3082             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3083                      ERR_R_EC_LIB);
3084             goto err;
3085         }
3086     }
3087
3088     if (ssl_derive(s, skey, ckey, 1) == 0) {
3089         /* SSLfatal() already called */
3090         goto err;
3091     }
3092
3093     ret = 1;
3094     EVP_PKEY_free(s->s3->tmp.pkey);
3095     s->s3->tmp.pkey = NULL;
3096  err:
3097     EVP_PKEY_free(ckey);
3098
3099     return ret;
3100 #else
3101     /* Should never happen */
3102     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_ECDHE,
3103              ERR_R_INTERNAL_ERROR);
3104     return 0;
3105 #endif
3106 }
3107
3108 static int tls_process_cke_srp(SSL *s, PACKET *pkt)
3109 {
3110 #ifndef OPENSSL_NO_SRP
3111     unsigned int i;
3112     const unsigned char *data;
3113
3114     if (!PACKET_get_net_2(pkt, &i)
3115         || !PACKET_get_bytes(pkt, &data, i)) {
3116         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3117                  SSL_R_BAD_SRP_A_LENGTH);
3118         return 0;
3119     }
3120     if ((s->srp_ctx.A = BN_bin2bn(data, i, NULL)) == NULL) {
3121         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3122                  ERR_R_BN_LIB);
3123         return 0;
3124     }
3125     if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0 || BN_is_zero(s->srp_ctx.A)) {
3126         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_TLS_PROCESS_CKE_SRP,
3127                  SSL_R_BAD_SRP_PARAMETERS);
3128         return 0;
3129     }
3130     OPENSSL_free(s->session->srp_username);
3131     s->session->srp_username = OPENSSL_strdup(s->srp_ctx.login);
3132     if (s->session->srp_username == NULL) {
3133         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3134                  ERR_R_MALLOC_FAILURE);
3135         return 0;
3136     }
3137
3138     if (!srp_generate_server_master_secret(s)) {
3139         /* SSLfatal() already called */
3140         return 0;
3141     }
3142
3143     return 1;
3144 #else
3145     /* Should never happen */
3146     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_SRP,
3147              ERR_R_INTERNAL_ERROR);
3148     return 0;
3149 #endif
3150 }
3151
3152 static int tls_process_cke_gost(SSL *s, PACKET *pkt)
3153 {
3154 #ifndef OPENSSL_NO_GOST
3155     EVP_PKEY_CTX *pkey_ctx;
3156     EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
3157     unsigned char premaster_secret[32];
3158     const unsigned char *start;
3159     size_t outlen = 32, inlen;
3160     unsigned long alg_a;
3161     int Ttag, Tclass;
3162     long Tlen;
3163     size_t sess_key_len;
3164     const unsigned char *data;
3165     int ret = 0;
3166
3167     /* Get our certificate private key */
3168     alg_a = s->s3->tmp.new_cipher->algorithm_auth;
3169     if (alg_a & SSL_aGOST12) {
3170         /*
3171          * New GOST ciphersuites have SSL_aGOST01 bit too
3172          */
3173         pk = s->cert->pkeys[SSL_PKEY_GOST12_512].privatekey;
3174         if (pk == NULL) {
3175             pk = s->cert->pkeys[SSL_PKEY_GOST12_256].privatekey;
3176         }
3177         if (pk == NULL) {
3178             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3179         }
3180     } else if (alg_a & SSL_aGOST01) {
3181         pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
3182     }
3183
3184     pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
3185     if (pkey_ctx == NULL) {
3186         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3187                  ERR_R_MALLOC_FAILURE);
3188         return 0;
3189     }
3190     if (EVP_PKEY_decrypt_init(pkey_ctx) <= 0) {
3191         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3192                  ERR_R_INTERNAL_ERROR);
3193         return 0;
3194     }
3195     /*
3196      * If client certificate is present and is of the same type, maybe
3197      * use it for key exchange.  Don't mind errors from
3198      * EVP_PKEY_derive_set_peer, because it is completely valid to use a
3199      * client certificate for authorization only.
3200      */
3201     client_pub_pkey = X509_get0_pubkey(s->session->peer);
3202     if (client_pub_pkey) {
3203         if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
3204             ERR_clear_error();
3205     }
3206     /* Decrypt session key */
3207     sess_key_len = PACKET_remaining(pkt);
3208     if (!PACKET_get_bytes(pkt, &data, sess_key_len)) {
3209         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3210                  ERR_R_INTERNAL_ERROR);
3211         goto err;
3212     }
3213     /* TODO(size_t): Convert this function */
3214     if (ASN1_get_object((const unsigned char **)&data, &Tlen, &Ttag,
3215                         &Tclass, (long)sess_key_len) != V_ASN1_CONSTRUCTED
3216         || Ttag != V_ASN1_SEQUENCE || Tclass != V_ASN1_UNIVERSAL) {
3217         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3218                  SSL_R_DECRYPTION_FAILED);
3219         goto err;
3220     }
3221     start = data;
3222     inlen = Tlen;
3223     if (EVP_PKEY_decrypt(pkey_ctx, premaster_secret, &outlen, start,
3224                          inlen) <= 0) {
3225         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3226                  SSL_R_DECRYPTION_FAILED);
3227         goto err;
3228     }
3229     /* Generate master secret */
3230     if (!ssl_generate_master_secret(s, premaster_secret,
3231                                     sizeof(premaster_secret), 0)) {
3232         /* SSLfatal() already called */
3233         goto err;
3234     }
3235     /* Check if pubkey from client certificate was used */
3236     if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2,
3237                           NULL) > 0)
3238         s->statem.no_cert_verify = 1;
3239
3240     ret = 1;
3241  err:
3242     EVP_PKEY_CTX_free(pkey_ctx);
3243     return ret;
3244 #else
3245     /* Should never happen */
3246     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CKE_GOST,
3247              ERR_R_INTERNAL_ERROR);
3248     return 0;
3249 #endif
3250 }
3251
3252 MSG_PROCESS_RETURN tls_process_client_key_exchange(SSL *s, PACKET *pkt)
3253 {
3254     unsigned long alg_k;
3255
3256     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
3257
3258     /* For PSK parse and retrieve identity, obtain PSK key */
3259     if ((alg_k & SSL_PSK) && !tls_process_cke_psk_preamble(s, pkt)) {
3260         /* SSLfatal() already called */
3261         goto err;
3262     }
3263
3264     if (alg_k & SSL_kPSK) {
3265         /* Identity extracted earlier: should be nothing left */
3266         if (PACKET_remaining(pkt) != 0) {
3267             SSLfatal(s, SSL_AD_DECODE_ERROR,
3268                      SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3269                      SSL_R_LENGTH_MISMATCH);
3270             goto err;
3271         }
3272         /* PSK handled by ssl_generate_master_secret */
3273         if (!ssl_generate_master_secret(s, NULL, 0, 0)) {
3274             /* SSLfatal() already called */
3275             goto err;
3276         }
3277     } else if (alg_k & (SSL_kRSA | SSL_kRSAPSK)) {
3278         if (!tls_process_cke_rsa(s, pkt)) {
3279             /* SSLfatal() already called */
3280             goto err;
3281         }
3282     } else if (alg_k & (SSL_kDHE | SSL_kDHEPSK)) {
3283         if (!tls_process_cke_dhe(s, pkt)) {
3284             /* SSLfatal() already called */
3285             goto err;
3286         }
3287     } else if (alg_k & (SSL_kECDHE | SSL_kECDHEPSK)) {
3288         if (!tls_process_cke_ecdhe(s, pkt)) {
3289             /* SSLfatal() already called */
3290             goto err;
3291         }
3292     } else if (alg_k & SSL_kSRP) {
3293         if (!tls_process_cke_srp(s, pkt)) {
3294             /* SSLfatal() already called */
3295             goto err;
3296         }
3297     } else if (alg_k & SSL_kGOST) {
3298         if (!tls_process_cke_gost(s, pkt)) {
3299             /* SSLfatal() already called */
3300             goto err;
3301         }
3302     } else {
3303         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3304                  SSL_F_TLS_PROCESS_CLIENT_KEY_EXCHANGE,
3305                  SSL_R_UNKNOWN_CIPHER_TYPE);
3306         goto err;
3307     }
3308
3309     return MSG_PROCESS_CONTINUE_PROCESSING;
3310  err:
3311 #ifndef OPENSSL_NO_PSK
3312     OPENSSL_clear_free(s->s3->tmp.psk, s->s3->tmp.psklen);
3313     s->s3->tmp.psk = NULL;
3314 #endif
3315     return MSG_PROCESS_ERROR;
3316 }
3317
3318 WORK_STATE tls_post_process_client_key_exchange(SSL *s, WORK_STATE wst)
3319 {
3320 #ifndef OPENSSL_NO_SCTP
3321     if (wst == WORK_MORE_A) {
3322         if (SSL_IS_DTLS(s)) {
3323             unsigned char sctpauthkey[64];
3324             char labelbuffer[sizeof(DTLS1_SCTP_AUTH_LABEL)];
3325             /*
3326              * Add new shared key for SCTP-Auth, will be ignored if no SCTP
3327              * used.
3328              */
3329             memcpy(labelbuffer, DTLS1_SCTP_AUTH_LABEL,
3330                    sizeof(DTLS1_SCTP_AUTH_LABEL));
3331
3332             if (SSL_export_keying_material(s, sctpauthkey,
3333                                            sizeof(sctpauthkey), labelbuffer,
3334                                            sizeof(labelbuffer), NULL, 0,
3335                                            0) <= 0) {
3336                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3337                          SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3338                          ERR_R_INTERNAL_ERROR);
3339                 return WORK_ERROR;
3340             }
3341
3342             BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_ADD_AUTH_KEY,
3343                      sizeof(sctpauthkey), sctpauthkey);
3344         }
3345     }
3346 #endif
3347
3348     if (s->statem.no_cert_verify || !s->session->peer) {
3349         /*
3350          * No certificate verify or no peer certificate so we no longer need
3351          * the handshake_buffer
3352          */
3353         if (!ssl3_digest_cached_records(s, 0)) {
3354             /* SSLfatal() already called */
3355             return WORK_ERROR;
3356         }
3357         return WORK_FINISHED_CONTINUE;
3358     } else {
3359         if (!s->s3->handshake_buffer) {
3360             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3361                      SSL_F_TLS_POST_PROCESS_CLIENT_KEY_EXCHANGE,
3362                      ERR_R_INTERNAL_ERROR);
3363             return WORK_ERROR;
3364         }
3365         /*
3366          * For sigalgs freeze the handshake buffer. If we support
3367          * extms we've done this already so this is a no-op
3368          */
3369         if (!ssl3_digest_cached_records(s, 1)) {
3370             /* SSLfatal() already called */
3371             return WORK_ERROR;
3372         }
3373     }
3374
3375     return WORK_FINISHED_CONTINUE;
3376 }
3377
3378 MSG_PROCESS_RETURN tls_process_client_certificate(SSL *s, PACKET *pkt)
3379 {
3380     int i;
3381     MSG_PROCESS_RETURN ret = MSG_PROCESS_ERROR;
3382     X509 *x = NULL;
3383     unsigned long l, llen;
3384     const unsigned char *certstart, *certbytes;
3385     STACK_OF(X509) *sk = NULL;
3386     PACKET spkt, context;
3387     size_t chainidx;
3388
3389     if ((sk = sk_X509_new_null()) == NULL) {
3390         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3391                  ERR_R_MALLOC_FAILURE);
3392         goto err;
3393     }
3394
3395     /* TODO(TLS1.3): For now we ignore the context. We need to verify this */
3396     if ((SSL_IS_TLS13(s) && !PACKET_get_length_prefixed_1(pkt, &context))
3397             || !PACKET_get_net_3(pkt, &llen)
3398             || !PACKET_get_sub_packet(pkt, &spkt, llen)
3399             || PACKET_remaining(pkt) != 0) {
3400         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3401                  SSL_R_LENGTH_MISMATCH);
3402         goto err;
3403     }
3404
3405     for (chainidx = 0; PACKET_remaining(&spkt) > 0; chainidx++) {
3406         if (!PACKET_get_net_3(&spkt, &l)
3407             || !PACKET_get_bytes(&spkt, &certbytes, l)) {
3408             SSLfatal(s, SSL_AD_DECODE_ERROR,
3409                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3410                      SSL_R_CERT_LENGTH_MISMATCH);
3411             goto err;
3412         }
3413
3414         certstart = certbytes;
3415         x = d2i_X509(NULL, (const unsigned char **)&certbytes, l);
3416         if (x == NULL) {
3417             SSLfatal(s, SSL_AD_DECODE_ERROR,
3418                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3419             goto err;
3420         }
3421         if (certbytes != (certstart + l)) {
3422             SSLfatal(s, SSL_AD_DECODE_ERROR,
3423                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3424                      SSL_R_CERT_LENGTH_MISMATCH);
3425             goto err;
3426         }
3427
3428         if (SSL_IS_TLS13(s)) {
3429             RAW_EXTENSION *rawexts = NULL;
3430             PACKET extensions;
3431
3432             if (!PACKET_get_length_prefixed_2(&spkt, &extensions)) {
3433                 SSLfatal(s, SSL_AD_DECODE_ERROR,
3434                          SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3435                          SSL_R_BAD_LENGTH);
3436                 goto err;
3437             }
3438             if (!tls_collect_extensions(s, &extensions,
3439                                         SSL_EXT_TLS1_3_CERTIFICATE, &rawexts,
3440                                         NULL, chainidx == 0)
3441                 || !tls_parse_all_extensions(s, SSL_EXT_TLS1_3_CERTIFICATE,
3442                                              rawexts, x, chainidx,
3443                                              PACKET_remaining(&spkt) == 0)) {
3444                 OPENSSL_free(rawexts);
3445                 goto err;
3446             }
3447             OPENSSL_free(rawexts);
3448         }
3449
3450         if (!sk_X509_push(sk, x)) {
3451             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3452                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3453                      ERR_R_MALLOC_FAILURE);
3454             goto err;
3455         }
3456         x = NULL;
3457     }
3458
3459     if (sk_X509_num(sk) <= 0) {
3460         /* TLS does not mind 0 certs returned */
3461         if (s->version == SSL3_VERSION) {
3462             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3463                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3464                      SSL_R_NO_CERTIFICATES_RETURNED);
3465             goto err;
3466         }
3467         /* Fail for TLS only if we required a certificate */
3468         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3469                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3470             SSLfatal(s, SSL_AD_CERTIFICATE_REQUIRED,
3471                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3472                      SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3473             goto err;
3474         }
3475         /* No client certificate so digest cached records */
3476         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s, 0)) {
3477             /* SSLfatal() already called */
3478             goto err;
3479         }
3480     } else {
3481         EVP_PKEY *pkey;
3482         i = ssl_verify_cert_chain(s, sk);
3483         if (i <= 0) {
3484             SSLfatal(s, ssl_verify_alarm_type(s->verify_result),
3485                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3486                      SSL_R_CERTIFICATE_VERIFY_FAILED);
3487             goto err;
3488         }
3489         if (i > 1) {
3490             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3491                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE, i);
3492             goto err;
3493         }
3494         pkey = X509_get0_pubkey(sk_X509_value(sk, 0));
3495         if (pkey == NULL) {
3496             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE,
3497                      SSL_F_TLS_PROCESS_CLIENT_CERTIFICATE,
3498                      SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3499             goto err;
3500         }
3501     }
3502
3503     X509_free(s->session->peer);
3504     s->session->peer = sk_X509_shift(sk);
3505     s->session->verify_result = s->verify_result;
3506
3507     sk_X509_pop_free(s->session->peer_chain, X509_free);
3508     s->session->peer_chain = sk;
3509
3510     /*
3511      * Freeze the handshake buffer. For <TLS1.3 we do this after the CKE
3512      * message
3513      */
3514     if (SSL_IS_TLS13(s) && !ssl3_digest_cached_records(s, 1)) {
3515         /* SSLfatal() already called */
3516         goto err;
3517     }
3518
3519     /*
3520      * Inconsistency alert: cert_chain does *not* include the peer's own
3521      * certificate, while we do include it in statem_clnt.c
3522      */
3523     sk = NULL;
3524
3525     /* Save the current hash state for when we receive the CertificateVerify */
3526     if (SSL_IS_TLS13(s)
3527             && !ssl_handshake_hash(s, s->cert_verify_hash,
3528                                    sizeof(s->cert_verify_hash),
3529                                    &s->cert_verify_hash_len)) {
3530         /* SSLfatal() already called */
3531         goto err;
3532     }
3533
3534     ret = MSG_PROCESS_CONTINUE_READING;
3535
3536  err:
3537     X509_free(x);
3538     sk_X509_pop_free(sk, X509_free);
3539     return ret;
3540 }
3541
3542 int tls_construct_server_certificate(SSL *s, WPACKET *pkt)
3543 {
3544     CERT_PKEY *cpk = s->s3->tmp.cert;
3545
3546     if (cpk == NULL) {
3547         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3548                  SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3549         return 0;
3550     }
3551
3552     /*
3553      * In TLSv1.3 the certificate chain is always preceded by a 0 length context
3554      * for the server Certificate message
3555      */
3556     if (SSL_IS_TLS13(s) && !WPACKET_put_bytes_u8(pkt, 0)) {
3557         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3558                  SSL_F_TLS_CONSTRUCT_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3559         return 0;
3560     }
3561     if (!ssl3_output_cert_chain(s, pkt, cpk)) {
3562         /* SSLfatal() already called */
3563         return 0;
3564     }
3565
3566     return 1;
3567 }
3568
3569 int tls_construct_new_session_ticket(SSL *s, WPACKET *pkt)
3570 {
3571     unsigned char *senc = NULL;
3572     EVP_CIPHER_CTX *ctx = NULL;
3573     HMAC_CTX *hctx = NULL;
3574     unsigned char *p, *encdata1, *encdata2, *macdata1, *macdata2;
3575     const unsigned char *const_p;
3576     int len, slen_full, slen, lenfinal;
3577     SSL_SESSION *sess;
3578     unsigned int hlen;
3579     SSL_CTX *tctx = s->session_ctx;
3580     unsigned char iv[EVP_MAX_IV_LENGTH];
3581     unsigned char key_name[TLSEXT_KEYNAME_LENGTH];
3582     int iv_len;
3583     size_t macoffset, macendoffset;
3584     union {
3585         unsigned char age_add_c[sizeof(uint32_t)];
3586         uint32_t age_add;
3587     } age_add_u;
3588
3589     if (SSL_IS_TLS13(s)) {
3590         if (ssl_randbytes(s, age_add_u.age_add_c, sizeof(age_add_u)) <= 0) {
3591             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3592                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3593                      ERR_R_INTERNAL_ERROR);
3594             goto err;
3595         }
3596         s->session->ext.tick_age_add = age_add_u.age_add;
3597        /*
3598         * ticket_nonce is set to a single 0 byte because we only ever send a
3599         * single ticket per connection. IMPORTANT: If we ever support multiple
3600         * tickets per connection then this will need to be changed.
3601         */
3602         OPENSSL_free(s->session->ext.tick_nonce);
3603         s->session->ext.tick_nonce = OPENSSL_zalloc(sizeof(char));
3604         if (s->session->ext.tick_nonce == NULL) {
3605             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3606                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3607                      ERR_R_MALLOC_FAILURE);
3608             goto err;
3609         }
3610         s->session->ext.tick_nonce_len = 1;
3611         s->session->time = (long)time(NULL);
3612         if (s->s3->alpn_selected != NULL) {
3613             OPENSSL_free(s->session->ext.alpn_selected);
3614             s->session->ext.alpn_selected =
3615                 OPENSSL_memdup(s->s3->alpn_selected, s->s3->alpn_selected_len);
3616             if (s->session->ext.alpn_selected == NULL) {
3617                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3618                          SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3619                          ERR_R_MALLOC_FAILURE);
3620                 goto err;
3621             }
3622             s->session->ext.alpn_selected_len = s->s3->alpn_selected_len;
3623         }
3624         s->session->ext.max_early_data = s->max_early_data;
3625     }
3626
3627     /* get session encoding length */
3628     slen_full = i2d_SSL_SESSION(s->session, NULL);
3629     /*
3630      * Some length values are 16 bits, so forget it if session is too
3631      * long
3632      */
3633     if (slen_full == 0 || slen_full > 0xFF00) {
3634         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3635                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3636         goto err;
3637     }
3638     senc = OPENSSL_malloc(slen_full);
3639     if (senc == NULL) {
3640         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3641                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3642         goto err;
3643     }
3644
3645     ctx = EVP_CIPHER_CTX_new();
3646     hctx = HMAC_CTX_new();
3647     if (ctx == NULL || hctx == NULL) {
3648         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3649                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_MALLOC_FAILURE);
3650         goto err;
3651     }
3652
3653     p = senc;
3654     if (!i2d_SSL_SESSION(s->session, &p)) {
3655         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3656                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3657         goto err;
3658     }
3659
3660     /*
3661      * create a fresh copy (not shared with other threads) to clean up
3662      */
3663     const_p = senc;
3664     sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3665     if (sess == NULL) {
3666         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3667                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3668         goto err;
3669     }
3670     sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3671
3672     slen = i2d_SSL_SESSION(sess, NULL);
3673     if (slen == 0 || slen > slen_full) {
3674         /* shouldn't ever happen */
3675         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3676                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3677         SSL_SESSION_free(sess);
3678         goto err;
3679     }
3680     p = senc;
3681     if (!i2d_SSL_SESSION(sess, &p)) {
3682         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3683                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3684         SSL_SESSION_free(sess);
3685         goto err;
3686     }
3687     SSL_SESSION_free(sess);
3688
3689     /*
3690      * Initialize HMAC and cipher contexts. If callback present it does
3691      * all the work otherwise use generated values from parent ctx.
3692      */
3693     if (tctx->ext.ticket_key_cb) {
3694         /* if 0 is returned, write an empty ticket */
3695         int ret = tctx->ext.ticket_key_cb(s, key_name, iv, ctx,
3696                                              hctx, 1);
3697
3698         if (ret == 0) {
3699
3700             /* Put timeout and length */
3701             if (!WPACKET_put_bytes_u32(pkt, 0)
3702                     || !WPACKET_put_bytes_u16(pkt, 0)) {
3703                 SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3704                          SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3705                          ERR_R_INTERNAL_ERROR);
3706                 goto err;
3707             }
3708             OPENSSL_free(senc);
3709             EVP_CIPHER_CTX_free(ctx);
3710             HMAC_CTX_free(hctx);
3711             return 1;
3712         }
3713         if (ret < 0) {
3714             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3715                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3716                      SSL_R_CALLBACK_FAILED);
3717             goto err;
3718         }
3719         iv_len = EVP_CIPHER_CTX_iv_length(ctx);
3720     } else {
3721         const EVP_CIPHER *cipher = EVP_aes_256_cbc();
3722
3723         iv_len = EVP_CIPHER_iv_length(cipher);
3724         if (ssl_randbytes(s, iv, iv_len) <= 0
3725                 || !EVP_EncryptInit_ex(ctx, cipher, NULL,
3726                                        tctx->ext.tick_aes_key, iv)
3727                 || !HMAC_Init_ex(hctx, tctx->ext.tick_hmac_key,
3728                                  sizeof(tctx->ext.tick_hmac_key),
3729                                  EVP_sha256(), NULL)) {
3730             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3731                      SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET,
3732                      ERR_R_INTERNAL_ERROR);
3733             goto err;
3734         }
3735         memcpy(key_name, tctx->ext.tick_key_name,
3736                sizeof(tctx->ext.tick_key_name));
3737     }
3738
3739     /*
3740      * Ticket lifetime hint: For TLSv1.2 this is advisory only and we leave this
3741      * unspecified for resumed session (for simplicity).
3742      * In TLSv1.3 we reset the "time" field above, and always specify the
3743      * timeout.
3744      */
3745     if (!WPACKET_put_bytes_u32(pkt,
3746                                (s->hit && !SSL_IS_TLS13(s))
3747                                ? 0 : s->session->timeout)
3748             || (SSL_IS_TLS13(s)
3749                 && (!WPACKET_put_bytes_u32(pkt, age_add_u.age_add)
3750                     || !WPACKET_sub_memcpy_u8(pkt, s->session->ext.tick_nonce,
3751                                               s->session->ext.tick_nonce_len)))
3752                /* Now the actual ticket data */
3753             || !WPACKET_start_sub_packet_u16(pkt)
3754             || !WPACKET_get_total_written(pkt, &macoffset)
3755                /* Output key name */
3756             || !WPACKET_memcpy(pkt, key_name, sizeof(key_name))
3757                /* output IV */
3758             || !WPACKET_memcpy(pkt, iv, iv_len)
3759             || !WPACKET_reserve_bytes(pkt, slen + EVP_MAX_BLOCK_LENGTH,
3760                                       &encdata1)
3761                /* Encrypt session data */
3762             || !EVP_EncryptUpdate(ctx, encdata1, &len, senc, slen)
3763             || !WPACKET_allocate_bytes(pkt, len, &encdata2)
3764             || encdata1 != encdata2
3765             || !EVP_EncryptFinal(ctx, encdata1 + len, &lenfinal)
3766             || !WPACKET_allocate_bytes(pkt, lenfinal, &encdata2)
3767             || encdata1 + len != encdata2
3768             || len + lenfinal > slen + EVP_MAX_BLOCK_LENGTH
3769             || !WPACKET_get_total_written(pkt, &macendoffset)
3770             || !HMAC_Update(hctx,
3771                             (unsigned char *)s->init_buf->data + macoffset,
3772                             macendoffset - macoffset)
3773             || !WPACKET_reserve_bytes(pkt, EVP_MAX_MD_SIZE, &macdata1)
3774             || !HMAC_Final(hctx, macdata1, &hlen)
3775             || hlen > EVP_MAX_MD_SIZE
3776             || !WPACKET_allocate_bytes(pkt, hlen, &macdata2)
3777             || macdata1 != macdata2
3778             || !WPACKET_close(pkt)) {
3779         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
3780                  SSL_F_TLS_CONSTRUCT_NEW_SESSION_TICKET, ERR_R_INTERNAL_ERROR);
3781         goto err;
3782     }
3783     if (SSL_IS_TLS13(s)
3784             && !tls_construct_extensions(s, pkt,
3785                                          SSL_EXT_TLS1_3_NEW_SESSION_TICKET,
3786                                          NULL, 0)) {
3787         /* SSLfatal() already called */
3788         goto err;
3789     }
3790     EVP_CIPHER_CTX_free(ctx);
3791     HMAC_CTX_free(hctx);
3792     OPENSSL_free(senc);
3793
3794     return 1;
3795  err:
3796     OPENSSL_free(senc);
3797     EVP_CIPHER_CTX_free(ctx);
3798     HMAC_CTX_free(hctx);
3799     return 0;
3800 }
3801
3802 /*
3803  * In TLSv1.3 this is called from the extensions code, otherwise it is used to
3804  * create a separate message. Returns 1 on success or 0 on failure.
3805  */
3806 int tls_construct_cert_status_body(SSL *s, WPACKET *pkt)
3807 {
3808     if (!WPACKET_put_bytes_u8(pkt, s->ext.status_type)
3809             || !WPACKET_sub_memcpy_u24(pkt, s->ext.ocsp.resp,
3810                                        s->ext.ocsp.resp_len)) {
3811         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_CONSTRUCT_CERT_STATUS_BODY,
3812                  ERR_R_INTERNAL_ERROR);
3813         return 0;
3814     }
3815
3816     return 1;
3817 }
3818
3819 int tls_construct_cert_status(SSL *s, WPACKET *pkt)
3820 {
3821     if (!tls_construct_cert_status_body(s, pkt)) {
3822         /* SSLfatal() already called */
3823         return 0;
3824     }
3825
3826     return 1;
3827 }
3828
3829 #ifndef OPENSSL_NO_NEXTPROTONEG
3830 /*
3831  * tls_process_next_proto reads a Next Protocol Negotiation handshake message.
3832  * It sets the next_proto member in s if found
3833  */
3834 MSG_PROCESS_RETURN tls_process_next_proto(SSL *s, PACKET *pkt)
3835 {
3836     PACKET next_proto, padding;
3837     size_t next_proto_len;
3838
3839     /*-
3840      * The payload looks like:
3841      *   uint8 proto_len;
3842      *   uint8 proto[proto_len];
3843      *   uint8 padding_len;
3844      *   uint8 padding[padding_len];
3845      */
3846     if (!PACKET_get_length_prefixed_1(pkt, &next_proto)
3847         || !PACKET_get_length_prefixed_1(pkt, &padding)
3848         || PACKET_remaining(pkt) > 0) {
3849         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
3850                  SSL_R_LENGTH_MISMATCH);
3851         return MSG_PROCESS_ERROR;
3852     }
3853
3854     if (!PACKET_memdup(&next_proto, &s->ext.npn, &next_proto_len)) {
3855         s->ext.npn_len = 0;
3856         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_NEXT_PROTO,
3857                  ERR_R_INTERNAL_ERROR);
3858         return MSG_PROCESS_ERROR;
3859     }
3860
3861     s->ext.npn_len = (unsigned char)next_proto_len;
3862
3863     return MSG_PROCESS_CONTINUE_READING;
3864 }
3865 #endif
3866
3867 static int tls_construct_encrypted_extensions(SSL *s, WPACKET *pkt)
3868 {
3869     if (!tls_construct_extensions(s, pkt, SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
3870                                   NULL, 0)) {
3871         /* SSLfatal() already called */
3872         return 0;
3873     }
3874
3875     return 1;
3876 }
3877
3878 MSG_PROCESS_RETURN tls_process_end_of_early_data(SSL *s, PACKET *pkt)
3879 {
3880     if (PACKET_remaining(pkt) != 0) {
3881         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3882                  SSL_R_LENGTH_MISMATCH);
3883         return MSG_PROCESS_ERROR;
3884     }
3885
3886     if (s->early_data_state != SSL_EARLY_DATA_READING
3887             && s->early_data_state != SSL_EARLY_DATA_READ_RETRY) {
3888         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3889                  ERR_R_INTERNAL_ERROR);
3890         return MSG_PROCESS_ERROR;
3891     }
3892
3893     /*
3894      * EndOfEarlyData signals a key change so the end of the message must be on
3895      * a record boundary.
3896      */
3897     if (RECORD_LAYER_processed_read_pending(&s->rlayer)) {
3898         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
3899                  SSL_F_TLS_PROCESS_END_OF_EARLY_DATA,
3900                  SSL_R_NOT_ON_RECORD_BOUNDARY);
3901         return MSG_PROCESS_ERROR;
3902     }
3903
3904     s->early_data_state = SSL_EARLY_DATA_FINISHED_READING;
3905     if (!s->method->ssl3_enc->change_cipher_state(s,
3906                 SSL3_CC_HANDSHAKE | SSL3_CHANGE_CIPHER_SERVER_READ)) {
3907         /* SSLfatal() already called */
3908         return MSG_PROCESS_ERROR;
3909     }
3910
3911     return MSG_PROCESS_CONTINUE_READING;
3912 }