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