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