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