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