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