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