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