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