6bc80d579b7ec720494e5e0e7472a8263f83083b
[openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_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 "internal/constant_time_locl.h"
155 #include <openssl/buffer.h>
156 #include <openssl/rand.h>
157 #include <openssl/objects.h>
158 #include <openssl/evp.h>
159 #include <openssl/hmac.h>
160 #include <openssl/x509.h>
161 #ifndef OPENSSL_NO_DH
162 # include <openssl/dh.h>
163 #endif
164 #include <openssl/bn.h>
165 #include <openssl/md5.h>
166
167 static STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
168     int num, STACK_OF(SSL_CIPHER) **skp, int sslv2format);
169
170
171 #ifndef OPENSSL_NO_SRP
172 static int ssl_check_srp_ext_ClientHello(SSL *s, int *al)
173 {
174     int ret = SSL_ERROR_NONE;
175
176     *al = SSL_AD_UNRECOGNIZED_NAME;
177
178     if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
179         (s->srp_ctx.TLS_ext_srp_username_callback != NULL)) {
180         if (s->srp_ctx.login == NULL) {
181             /*
182              * RFC 5054 says SHOULD reject, we do so if There is no srp
183              * login name
184              */
185             ret = SSL3_AL_FATAL;
186             *al = SSL_AD_UNKNOWN_PSK_IDENTITY;
187         } else {
188             ret = SSL_srp_server_param_with_username(s, al);
189         }
190     }
191     return ret;
192 }
193 #endif
194
195 int ssl3_accept(SSL *s)
196 {
197     BUF_MEM *buf;
198     unsigned long alg_k, Time = (unsigned long)time(NULL);
199     void (*cb) (const SSL *ssl, int type, int val) = NULL;
200     int ret = -1;
201     int new_state, state, skip = 0;
202
203     RAND_add(&Time, sizeof(Time), 0);
204     ERR_clear_error();
205     clear_sys_error();
206
207     if (s->info_callback != NULL)
208         cb = s->info_callback;
209     else if (s->ctx->info_callback != NULL)
210         cb = s->ctx->info_callback;
211
212     /* init things to blank */
213     s->in_handshake++;
214     if (!SSL_in_init(s) || SSL_in_before(s)) {
215         if (!SSL_clear(s))
216             return -1;
217     }
218
219 #ifndef OPENSSL_NO_HEARTBEATS
220     /*
221      * If we're awaiting a HeartbeatResponse, pretend we already got and
222      * don't await it anymore, because Heartbeats don't make sense during
223      * handshakes anyway.
224      */
225     if (s->tlsext_hb_pending) {
226         s->tlsext_hb_pending = 0;
227         s->tlsext_hb_seq++;
228     }
229 #endif
230
231     for (;;) {
232         state = s->state;
233
234         switch (s->state) {
235         case SSL_ST_RENEGOTIATE:
236             s->renegotiate = 1;
237             /* s->state=SSL_ST_ACCEPT; */
238
239         case SSL_ST_BEFORE:
240         case SSL_ST_ACCEPT:
241         case SSL_ST_BEFORE | SSL_ST_ACCEPT:
242         case SSL_ST_OK | SSL_ST_ACCEPT:
243
244             s->server = 1;
245             if (cb != NULL)
246                 cb(s, SSL_CB_HANDSHAKE_START, 1);
247
248             if ((s->version >> 8 != 3) && s->version != TLS_ANY_VERSION) {
249                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
250                 s->state = SSL_ST_ERR;
251                 return -1;
252             }
253
254             if (!ssl_security(s, SSL_SECOP_VERSION, 0, s->version, NULL)) {
255                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_VERSION_TOO_LOW);
256                 return -1;
257             }
258
259             s->type = SSL_ST_ACCEPT;
260
261             if (s->init_buf == NULL) {
262                 if ((buf = BUF_MEM_new()) == NULL) {
263                     ret = -1;
264                     s->state = SSL_ST_ERR;
265                     goto end;
266                 }
267                 if (!BUF_MEM_grow(buf, SSL3_RT_MAX_PLAIN_LENGTH)) {
268                     BUF_MEM_free(buf);
269                     ret = -1;
270                     s->state = SSL_ST_ERR;
271                     goto end;
272                 }
273                 s->init_buf = buf;
274             }
275
276             if (!ssl3_setup_buffers(s)) {
277                 ret = -1;
278                 s->state = SSL_ST_ERR;
279                 goto end;
280             }
281
282             s->init_num = 0;
283             s->s3->flags &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
284             s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
285             /*
286              * Should have been reset by ssl3_get_finished, too.
287              */
288             s->s3->change_cipher_spec = 0;
289
290             if (s->state != SSL_ST_RENEGOTIATE) {
291                 /*
292                  * Ok, we now need to push on a buffering BIO so that the
293                  * output is sent in a way that TCP likes :-)
294                  */
295                 if (!ssl_init_wbio_buffer(s, 1)) {
296                     ret = -1;
297                     s->state = SSL_ST_ERR;
298                     goto end;
299                 }
300
301                 ssl3_init_finished_mac(s);
302                 s->state = SSL3_ST_SR_CLNT_HELLO_A;
303                 s->ctx->stats.sess_accept++;
304             } else if (!s->s3->send_connection_binding &&
305                        !(s->options &
306                          SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
307                 /*
308                  * Server attempting to renegotiate with client that doesn't
309                  * support secure renegotiation.
310                  */
311                 SSLerr(SSL_F_SSL3_ACCEPT,
312                        SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
313                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
314                 ret = -1;
315                 s->state = SSL_ST_ERR;
316                 goto end;
317             } else {
318                 /*
319                  * s->state == SSL_ST_RENEGOTIATE, we will just send a
320                  * HelloRequest
321                  */
322                 s->ctx->stats.sess_accept_renegotiate++;
323                 s->state = SSL3_ST_SW_HELLO_REQ_A;
324             }
325             break;
326
327         case SSL3_ST_SW_HELLO_REQ_A:
328         case SSL3_ST_SW_HELLO_REQ_B:
329
330             s->shutdown = 0;
331             ret = ssl3_send_hello_request(s);
332             if (ret <= 0)
333                 goto end;
334             s->s3->tmp.next_state = SSL3_ST_SW_HELLO_REQ_C;
335             s->state = SSL3_ST_SW_FLUSH;
336             s->init_num = 0;
337
338             ssl3_init_finished_mac(s);
339             break;
340
341         case SSL3_ST_SW_HELLO_REQ_C:
342             s->state = SSL_ST_OK;
343             break;
344
345         case SSL3_ST_SR_CLNT_HELLO_A:
346         case SSL3_ST_SR_CLNT_HELLO_B:
347         case SSL3_ST_SR_CLNT_HELLO_C:
348
349             ret = ssl3_get_client_hello(s);
350             if (ret <= 0)
351                 goto end;
352 #ifndef OPENSSL_NO_SRP
353             s->state = SSL3_ST_SR_CLNT_HELLO_D;
354         case SSL3_ST_SR_CLNT_HELLO_D:
355             {
356                 int al;
357                 if ((ret = ssl_check_srp_ext_ClientHello(s, &al)) < 0) {
358                     /*
359                      * callback indicates firther work to be done
360                      */
361                     s->rwstate = SSL_X509_LOOKUP;
362                     goto end;
363                 }
364                 if (ret != SSL_ERROR_NONE) {
365                     ssl3_send_alert(s, SSL3_AL_FATAL, al);
366                     /*
367                      * This is not really an error but the only means to for
368                      * a client to detect whether srp is supported.
369                      */
370                     if (al != TLS1_AD_UNKNOWN_PSK_IDENTITY)
371                         SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_CLIENTHELLO_TLSEXT);
372                     ret = SSL_TLSEXT_ERR_ALERT_FATAL;
373                     ret = -1;
374                     s->state = SSL_ST_ERR;
375                     goto end;
376                 }
377             }
378 #endif
379
380             s->renegotiate = 2;
381             s->state = SSL3_ST_SW_SRVR_HELLO_A;
382             s->init_num = 0;
383             break;
384
385         case SSL3_ST_SW_SRVR_HELLO_A:
386         case SSL3_ST_SW_SRVR_HELLO_B:
387             ret = ssl3_send_server_hello(s);
388             if (ret <= 0)
389                 goto end;
390 #ifndef OPENSSL_NO_TLSEXT
391             if (s->hit) {
392                 if (s->tlsext_ticket_expected)
393                     s->state = SSL3_ST_SW_SESSION_TICKET_A;
394                 else
395                     s->state = SSL3_ST_SW_CHANGE_A;
396             }
397 #else
398             if (s->hit)
399                 s->state = SSL3_ST_SW_CHANGE_A;
400 #endif
401             else
402                 s->state = SSL3_ST_SW_CERT_A;
403             s->init_num = 0;
404             break;
405
406         case SSL3_ST_SW_CERT_A:
407         case SSL3_ST_SW_CERT_B:
408             /* Check if it is anon DH or anon ECDH, */
409             /* normal PSK or SRP */
410             if (!
411                 (s->s3->tmp.
412                  new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
413 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
414                 ret = ssl3_send_server_certificate(s);
415                 if (ret <= 0)
416                     goto end;
417 #ifndef OPENSSL_NO_TLSEXT
418                 if (s->tlsext_status_expected)
419                     s->state = SSL3_ST_SW_CERT_STATUS_A;
420                 else
421                     s->state = SSL3_ST_SW_KEY_EXCH_A;
422             } else {
423                 skip = 1;
424                 s->state = SSL3_ST_SW_KEY_EXCH_A;
425             }
426 #else
427             } else
428                 skip = 1;
429
430             s->state = SSL3_ST_SW_KEY_EXCH_A;
431 #endif
432             s->init_num = 0;
433             break;
434
435         case SSL3_ST_SW_KEY_EXCH_A:
436         case SSL3_ST_SW_KEY_EXCH_B:
437             alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
438
439             /*
440              * clear this, it may get reset by
441              * send_server_key_exchange
442              */
443             s->s3->tmp.use_rsa_tmp = 0;
444
445             /*
446              * only send if a DH key exchange, fortezza or RSA but we have a
447              * sign only certificate PSK: may send PSK identity hints For
448              * ECC ciphersuites, we send a serverKeyExchange message only if
449              * the cipher suite is either ECDH-anon or ECDHE. In other cases,
450              * the server certificate contains the server's public key for
451              * key exchange.
452              */
453             if (0
454                 /*
455                  * PSK: send ServerKeyExchange if PSK identity hint if
456                  * provided
457                  */
458 #ifndef OPENSSL_NO_PSK
459                 || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
460 #endif
461 #ifndef OPENSSL_NO_SRP
462                 /* SRP: send ServerKeyExchange */
463                 || (alg_k & SSL_kSRP)
464 #endif
465                 || (alg_k & SSL_kDHE)
466                 || (alg_k & SSL_kECDHE)
467                 || ((alg_k & SSL_kRSA)
468                     && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
469                         || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
470                             && EVP_PKEY_size(s->cert->pkeys
471                                              [SSL_PKEY_RSA_ENC].privatekey) *
472                             8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
473                         )
474                     )
475                 )
476                 ) {
477                 ret = ssl3_send_server_key_exchange(s);
478                 if (ret <= 0)
479                     goto end;
480             } else
481                 skip = 1;
482
483             s->state = SSL3_ST_SW_CERT_REQ_A;
484             s->init_num = 0;
485             break;
486
487         case SSL3_ST_SW_CERT_REQ_A:
488         case SSL3_ST_SW_CERT_REQ_B:
489             if (                /* don't request cert unless asked for it: */
490                    !(s->verify_mode & SSL_VERIFY_PEER) ||
491                    /*
492                     * if SSL_VERIFY_CLIENT_ONCE is set, don't request cert
493                     * during re-negotiation:
494                     */
495                    ((s->session->peer != NULL) &&
496                     (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
497                    /*
498                     * never request cert in anonymous ciphersuites (see
499                     * section "Certificate request" in SSL 3 drafts and in
500                     * RFC 2246):
501                     */
502                    ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
503                    /*
504                     * ... except when the application insists on
505                     * verification (against the specs, but s3_clnt.c accepts
506                     * this for SSL 3)
507                     */
508                    !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
509                    /* don't request certificate for SRP auth */
510                    (s->s3->tmp.new_cipher->algorithm_auth & SSL_aSRP)
511                    /*
512                     * With normal PSK Certificates and Certificate Requests
513                     * are omitted
514                     */
515                    || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
516                 /* no cert request */
517                 skip = 1;
518                 s->s3->tmp.cert_request = 0;
519                 s->state = SSL3_ST_SW_SRVR_DONE_A;
520                 if (s->s3->handshake_buffer) {
521                     if (!ssl3_digest_cached_records(s)) {
522                         s->state = SSL_ST_ERR;
523                         return -1;
524                     }
525                 }
526             } else {
527                 s->s3->tmp.cert_request = 1;
528                 ret = ssl3_send_certificate_request(s);
529                 if (ret <= 0)
530                     goto end;
531                 s->state = SSL3_ST_SW_SRVR_DONE_A;
532                 s->init_num = 0;
533             }
534             break;
535
536         case SSL3_ST_SW_SRVR_DONE_A:
537         case SSL3_ST_SW_SRVR_DONE_B:
538             ret = ssl3_send_server_done(s);
539             if (ret <= 0)
540                 goto end;
541             s->s3->tmp.next_state = SSL3_ST_SR_CERT_A;
542             s->state = SSL3_ST_SW_FLUSH;
543             s->init_num = 0;
544             break;
545
546         case SSL3_ST_SW_FLUSH:
547
548             /*
549              * This code originally checked to see if any data was pending
550              * using BIO_CTRL_INFO and then flushed. This caused problems as
551              * documented in PR#1939. The proposed fix doesn't completely
552              * resolve this issue as buggy implementations of
553              * BIO_CTRL_PENDING still exist. So instead we just flush
554              * unconditionally.
555              */
556
557             s->rwstate = SSL_WRITING;
558             if (BIO_flush(s->wbio) <= 0) {
559                 ret = -1;
560                 goto end;
561             }
562             s->rwstate = SSL_NOTHING;
563
564             s->state = s->s3->tmp.next_state;
565             break;
566
567         case SSL3_ST_SR_CERT_A:
568         case SSL3_ST_SR_CERT_B:
569             if (s->s3->tmp.cert_request) {
570                 ret = ssl3_get_client_certificate(s);
571                 if (ret <= 0)
572                     goto end;
573             }
574             s->init_num = 0;
575             s->state = SSL3_ST_SR_KEY_EXCH_A;
576             break;
577
578         case SSL3_ST_SR_KEY_EXCH_A:
579         case SSL3_ST_SR_KEY_EXCH_B:
580             ret = ssl3_get_client_key_exchange(s);
581             if (ret <= 0)
582                 goto end;
583             if (ret == 2) {
584                 /*
585                  * For the ECDH ciphersuites when the client sends its ECDH
586                  * pub key in a certificate, the CertificateVerify message is
587                  * not sent. Also for GOST ciphersuites when the client uses
588                  * its key from the certificate for key exchange.
589                  */
590 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
591                 s->state = SSL3_ST_SR_FINISHED_A;
592 #else
593                 if (s->s3->next_proto_neg_seen)
594                     s->state = SSL3_ST_SR_NEXT_PROTO_A;
595                 else
596                     s->state = SSL3_ST_SR_FINISHED_A;
597 #endif
598                 s->init_num = 0;
599             } else if (SSL_USE_SIGALGS(s)) {
600                 s->state = SSL3_ST_SR_CERT_VRFY_A;
601                 s->init_num = 0;
602                 if (!s->session->peer)
603                     break;
604                 if (!s->s3->handshake_buffer) {
605                     SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
606                     s->state = SSL_ST_ERR;
607                     return -1;
608                 }
609                 /*
610                  * For sigalgs freeze the handshake buffer. If we support
611                  * extms we've done this already.
612                  */
613                 if (!(s->s3->flags & SSL_SESS_FLAG_EXTMS)) {
614                     s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
615                     if (!ssl3_digest_cached_records(s)) {
616                         s->state = SSL_ST_ERR;
617                         return -1;
618                     }
619                 }
620             } else {
621                 int offset = 0;
622                 int dgst_num;
623
624                 s->state = SSL3_ST_SR_CERT_VRFY_A;
625                 s->init_num = 0;
626
627                 /*
628                  * We need to get hashes here so if there is a client cert,
629                  * it can be verified FIXME - digest processing for
630                  * CertificateVerify should be generalized. But it is next
631                  * step
632                  */
633                 if (s->s3->handshake_buffer) {
634                     if (!ssl3_digest_cached_records(s)) {
635                         s->state = SSL_ST_ERR;
636                         return -1;
637                     }
638                 }
639                 for (dgst_num = 0; dgst_num < SSL_MAX_DIGEST; dgst_num++)
640                     if (s->s3->handshake_dgst[dgst_num]) {
641                         int dgst_size;
642
643                         s->method->ssl3_enc->cert_verify_mac(s,
644                                                              EVP_MD_CTX_type
645                                                              (s->
646                                                               s3->handshake_dgst
647                                                               [dgst_num]),
648                                                              &(s->s3->
649                                                                tmp.cert_verify_md
650                                                                [offset]));
651                         dgst_size =
652                             EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
653                         if (dgst_size < 0) {
654                             s->state = SSL_ST_ERR;
655                             ret = -1;
656                             goto end;
657                         }
658                         offset += dgst_size;
659                     }
660             }
661             break;
662
663         case SSL3_ST_SR_CERT_VRFY_A:
664         case SSL3_ST_SR_CERT_VRFY_B:
665             ret = ssl3_get_cert_verify(s);
666             if (ret <= 0)
667                 goto end;
668
669 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
670             s->state = SSL3_ST_SR_FINISHED_A;
671 #else
672             if (s->s3->next_proto_neg_seen)
673                 s->state = SSL3_ST_SR_NEXT_PROTO_A;
674             else
675                 s->state = SSL3_ST_SR_FINISHED_A;
676 #endif
677             s->init_num = 0;
678             break;
679
680 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
681         case SSL3_ST_SR_NEXT_PROTO_A:
682         case SSL3_ST_SR_NEXT_PROTO_B:
683             /*
684              * Enable CCS for NPN. Receiving a CCS clears the flag, so make
685              * sure not to re-enable it to ban duplicates. This *should* be the
686              * first time we have received one - but we check anyway to be
687              * cautious.
688              * s->s3->change_cipher_spec is set when a CCS is
689              * processed in s3_pkt.c, and remains set until
690              * the client's Finished message is read.
691              */
692             if (!s->s3->change_cipher_spec)
693                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
694
695             ret = ssl3_get_next_proto(s);
696             if (ret <= 0)
697                 goto end;
698             s->init_num = 0;
699             s->state = SSL3_ST_SR_FINISHED_A;
700             break;
701 #endif
702
703         case SSL3_ST_SR_FINISHED_A:
704         case SSL3_ST_SR_FINISHED_B:
705             /*
706              * Enable CCS for handshakes without NPN. In NPN the CCS flag has
707              * already been set. Receiving a CCS clears the flag, so make
708              * sure not to re-enable it to ban duplicates.
709              * s->s3->change_cipher_spec is set when a CCS is
710              * processed in s3_pkt.c, and remains set until
711              * the client's Finished message is read.
712              */
713             if (!s->s3->change_cipher_spec)
714                 s->s3->flags |= SSL3_FLAGS_CCS_OK;
715             ret = ssl3_get_finished(s, SSL3_ST_SR_FINISHED_A,
716                                     SSL3_ST_SR_FINISHED_B);
717             if (ret <= 0)
718                 goto end;
719             if (s->hit)
720                 s->state = SSL_ST_OK;
721 #ifndef OPENSSL_NO_TLSEXT
722             else if (s->tlsext_ticket_expected)
723                 s->state = SSL3_ST_SW_SESSION_TICKET_A;
724 #endif
725             else
726                 s->state = SSL3_ST_SW_CHANGE_A;
727             s->init_num = 0;
728             break;
729
730 #ifndef OPENSSL_NO_TLSEXT
731         case SSL3_ST_SW_SESSION_TICKET_A:
732         case SSL3_ST_SW_SESSION_TICKET_B:
733             ret = ssl3_send_newsession_ticket(s);
734             if (ret <= 0)
735                 goto end;
736             s->state = SSL3_ST_SW_CHANGE_A;
737             s->init_num = 0;
738             break;
739
740         case SSL3_ST_SW_CERT_STATUS_A:
741         case SSL3_ST_SW_CERT_STATUS_B:
742             ret = ssl3_send_cert_status(s);
743             if (ret <= 0)
744                 goto end;
745             s->state = SSL3_ST_SW_KEY_EXCH_A;
746             s->init_num = 0;
747             break;
748
749 #endif
750
751         case SSL3_ST_SW_CHANGE_A:
752         case SSL3_ST_SW_CHANGE_B:
753
754             s->session->cipher = s->s3->tmp.new_cipher;
755             if (!s->method->ssl3_enc->setup_key_block(s)) {
756                 ret = -1;
757                 s->state = SSL_ST_ERR;
758                 goto end;
759             }
760
761             ret = ssl3_send_change_cipher_spec(s,
762                                                SSL3_ST_SW_CHANGE_A,
763                                                SSL3_ST_SW_CHANGE_B);
764
765             if (ret <= 0)
766                 goto end;
767             s->state = SSL3_ST_SW_FINISHED_A;
768             s->init_num = 0;
769
770             if (!s->method->ssl3_enc->change_cipher_state(s,
771                                                           SSL3_CHANGE_CIPHER_SERVER_WRITE))
772             {
773                 ret = -1;
774                 s->state = SSL_ST_ERR;
775                 goto end;
776             }
777
778             break;
779
780         case SSL3_ST_SW_FINISHED_A:
781         case SSL3_ST_SW_FINISHED_B:
782             ret = ssl3_send_finished(s,
783                                      SSL3_ST_SW_FINISHED_A,
784                                      SSL3_ST_SW_FINISHED_B,
785                                      s->method->
786                                      ssl3_enc->server_finished_label,
787                                      s->method->
788                                      ssl3_enc->server_finished_label_len);
789             if (ret <= 0)
790                 goto end;
791             s->state = SSL3_ST_SW_FLUSH;
792             if (s->hit) {
793 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
794                 s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
795 #else
796                 if (s->s3->next_proto_neg_seen) {
797                     s->s3->tmp.next_state = SSL3_ST_SR_NEXT_PROTO_A;
798                 } else
799                     s->s3->tmp.next_state = SSL3_ST_SR_FINISHED_A;
800 #endif
801             } else
802                 s->s3->tmp.next_state = SSL_ST_OK;
803             s->init_num = 0;
804             break;
805
806         case SSL_ST_OK:
807             /* clean a few things up */
808             ssl3_cleanup_key_block(s);
809
810             BUF_MEM_free(s->init_buf);
811             s->init_buf = NULL;
812
813             /* remove buffering on output */
814             ssl_free_wbio_buffer(s);
815
816             s->init_num = 0;
817
818             if (s->renegotiate == 2) { /* skipped if we just sent a
819                                         * HelloRequest */
820                 s->renegotiate = 0;
821                 s->new_session = 0;
822
823                 ssl_update_cache(s, SSL_SESS_CACHE_SERVER);
824
825                 s->ctx->stats.sess_accept_good++;
826                 /* s->server=1; */
827                 s->handshake_func = ssl3_accept;
828
829                 if (cb != NULL)
830                     cb(s, SSL_CB_HANDSHAKE_DONE, 1);
831             }
832
833             ret = 1;
834             goto end;
835             /* break; */
836
837         case SSL_ST_ERR:
838         default:
839             SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNKNOWN_STATE);
840             ret = -1;
841             goto end;
842             /* break; */
843         }
844
845         if (!s->s3->tmp.reuse_message && !skip) {
846             if (s->debug) {
847                 if ((ret = BIO_flush(s->wbio)) <= 0)
848                     goto end;
849             }
850
851             if ((cb != NULL) && (s->state != state)) {
852                 new_state = s->state;
853                 s->state = state;
854                 cb(s, SSL_CB_ACCEPT_LOOP, 1);
855                 s->state = new_state;
856             }
857         }
858         skip = 0;
859     }
860  end:
861     /* BIO_flush(s->wbio); */
862
863     s->in_handshake--;
864     if (cb != NULL)
865         cb(s, SSL_CB_ACCEPT_EXIT, ret);
866     return (ret);
867 }
868
869 int ssl3_send_hello_request(SSL *s)
870 {
871
872     if (s->state == SSL3_ST_SW_HELLO_REQ_A) {
873         if (!ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0)) {
874             SSLerr(SSL_F_SSL3_SEND_HELLO_REQUEST, ERR_R_INTERNAL_ERROR);
875             return -1;
876         }
877         s->state = SSL3_ST_SW_HELLO_REQ_B;
878     }
879
880     /* SSL3_ST_SW_HELLO_REQ_B */
881     return ssl_do_write(s);
882 }
883
884 int ssl3_get_client_hello(SSL *s)
885 {
886     int i, complen, j, ok, al = SSL_AD_INTERNAL_ERROR, ret = -1;
887     unsigned int cookie_len;
888     long n;
889     unsigned long id;
890     unsigned char *p, *d;
891     SSL_CIPHER *c;
892 #ifndef OPENSSL_NO_COMP
893     unsigned char *q = NULL;
894     SSL_COMP *comp = NULL;
895 #endif
896     STACK_OF(SSL_CIPHER) *ciphers = NULL;
897     int protverr = 1;
898
899     if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
900         goto retry_cert;
901
902     /*
903      * We do this so that we will respond with our native type. If we are
904      * TLSv1 and we get SSLv3, we will respond with TLSv1, This down
905      * switching should be handled by a different method. If we are SSLv3, we
906      * will respond with SSLv3, even if prompted with TLSv1.
907      */
908     if (s->state == SSL3_ST_SR_CLNT_HELLO_A) {
909         s->state = SSL3_ST_SR_CLNT_HELLO_B;
910     }
911     s->first_packet = 1;
912     n = s->method->ssl_get_message(s,
913                                    SSL3_ST_SR_CLNT_HELLO_B,
914                                    SSL3_ST_SR_CLNT_HELLO_C,
915                                    SSL3_MT_CLIENT_HELLO,
916                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
917
918     if (!ok)
919         return ((int)n);
920     s->first_packet = 0;
921     d = p = (unsigned char *)s->init_msg;
922
923     /* First lets get s->client_version set correctly */
924     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
925         /*-
926          * An SSLv3/TLSv1 backwards-compatible CLIENT-HELLO in an SSLv2
927          * header is sent directly on the wire, not wrapped as a TLS
928          * record. Our record layer just processes the message length and passes
929          * the rest right through. Its format is:
930          * Byte  Content
931          * 0-1   msg_length - decoded by the record layer
932          * 2     msg_type - s->init_msg points here
933          * 3-4   version
934          * 5-6   cipher_spec_length
935          * 7-8   session_id_length
936          * 9-10  challenge_length
937          * ...   ...
938          */
939
940         if (p[0] != SSL2_MT_CLIENT_HELLO) {
941             /*
942              * Should never happen. We should have tested this in the record
943              * layer in order to have determined that this is a SSLv2 record
944              * in the first place
945              */
946             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
947             goto err;
948         }
949
950         if ((p[1] == 0x00) && (p[2] == 0x02)) {
951             /* This is real SSLv2. We don't support it. */
952             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
953             goto err;
954         } else if (p[1] == SSL3_VERSION_MAJOR) {
955             /* SSLv3/TLS */
956             s->client_version = (((int)p[1]) << 8) | (int)p[2];
957         } else {
958             /* No idea what protocol this is */
959             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
960             goto err;
961         }
962     } else {
963         /*
964          * 2 bytes for client version, SSL3_RANDOM_SIZE bytes for random, 1 byte
965          * for session id length
966          */
967         if (n < 2 + SSL3_RANDOM_SIZE + 1) {
968             al = SSL_AD_DECODE_ERROR;
969             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
970             goto f_err;
971         }
972
973         /*
974          * use version from inside client hello, not from record header (may
975          * differ: see RFC 2246, Appendix E, second paragraph)
976          */
977         s->client_version = (((int)p[0]) << 8) | (int)p[1];
978     }
979
980     /* Do SSL/TLS version negotiation if applicable */
981     if (!SSL_IS_DTLS(s)) {
982         if (s->version != TLS_ANY_VERSION) {
983             if (s->client_version >= s->version) {
984                 protverr = 0;
985             }
986         } else if (s->client_version >= SSL3_VERSION) {
987             switch(s->client_version) {
988             default:
989             case TLS1_2_VERSION:
990                 if(!(s->options & SSL_OP_NO_TLSv1_2)) {
991                     s->version = TLS1_2_VERSION;
992                     s->method = TLSv1_2_server_method();
993                     protverr = 0;
994                     break;
995                 }
996                 /* Deliberately fall through */
997             case TLS1_1_VERSION:
998                 if(!(s->options & SSL_OP_NO_TLSv1_1)) {
999                     s->version = TLS1_1_VERSION;
1000                     s->method = TLSv1_1_server_method();
1001                     protverr = 0;
1002                     break;
1003                 }
1004                 /* Deliberately fall through */
1005             case TLS1_VERSION:
1006                 if(!(s->options & SSL_OP_NO_TLSv1)) {
1007                     s->version = TLS1_VERSION;
1008                     s->method = TLSv1_server_method();
1009                     protverr = 0;
1010                     break;
1011                 }
1012                 /* Deliberately fall through */
1013             case SSL3_VERSION:
1014 #ifndef OPENSSL_NO_SSL3
1015                 if(!(s->options & SSL_OP_NO_SSLv3)) {
1016                     s->version = SSL3_VERSION;
1017                     s->method = SSLv3_server_method();
1018                     protverr = 0;
1019                     break;
1020                 }
1021 #else
1022                 break;
1023 #endif
1024             }
1025         }
1026     } else if (s->client_version <= s->version
1027                 || s->method->version == DTLS_ANY_VERSION) {
1028         /*
1029          * For DTLS we just check versions are potentially compatible. Version
1030          * negotiation comes later.
1031          */
1032         protverr = 0;
1033     }
1034
1035     if (protverr) {
1036         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_UNKNOWN_PROTOCOL);
1037         if ((!s->enc_write_ctx && !s->write_hash)) {
1038             /*
1039              * similar to ssl3_get_record, send alert using remote version
1040              * number
1041              */
1042             s->version = s->client_version;
1043         }
1044         al = SSL_AD_PROTOCOL_VERSION;
1045         goto f_err;
1046     }
1047
1048     if (RECORD_LAYER_is_sslv2_record(&s->rlayer)) {
1049         /*
1050          * Handle an SSLv2 backwards compatible ClientHello
1051          * Note, this is only for SSLv3+ using the backward compatible format.
1052          * Real SSLv2 is not supported, and is rejected above.
1053          */
1054         unsigned int csl, sil, cl;
1055
1056         p += 3;
1057         n2s(p, csl);
1058         n2s(p, sil);
1059         n2s(p, cl);
1060
1061         if (csl + sil + cl + MIN_SSL2_RECORD_LEN != (unsigned int) n) {
1062             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_RECORD_LENGTH_MISMATCH);
1063             al = SSL_AD_DECODE_ERROR;
1064             goto f_err;
1065         }
1066
1067         if (csl == 0) {
1068             /* we need at least one cipher */
1069             al = SSL_AD_ILLEGAL_PARAMETER;
1070             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1071             goto f_err;
1072         }
1073
1074         if (ssl_bytes_to_cipher_list(s, p, csl, &(ciphers), 1) == NULL) {
1075             goto err;
1076         }
1077
1078         /*
1079          * Ignore any session id. We don't allow resumption in a backwards
1080          * compatible ClientHello
1081          */
1082         s->hit = 0;
1083
1084         if (!ssl_get_new_session(s, 1))
1085             goto err;
1086
1087         /* Load the client random */
1088         i = (cl > SSL3_RANDOM_SIZE) ? SSL3_RANDOM_SIZE : cl;
1089         memset(s->s3->client_random, 0, SSL3_RANDOM_SIZE);
1090         memcpy(s->s3->client_random, &(p[csl + sil]), i);
1091
1092         /* Set p to end of packet to ensure we don't look for extensions */
1093         p = d + n;
1094
1095         /* No compression, so set complen to 0 */
1096         complen = 0;
1097     } else {
1098         /* If we get here we've got SSLv3+ in an SSLv3+ record */
1099
1100         p += 2;
1101
1102         /*
1103          * If we require cookies and this ClientHello doesn't contain one, just
1104          * return since we do not want to allocate any memory yet. So check
1105          * cookie length...
1106          */
1107         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) {
1108             unsigned int session_length, cookie_length;
1109
1110             session_length = *(p + SSL3_RANDOM_SIZE);
1111
1112             if (p + SSL3_RANDOM_SIZE + session_length + 1 >= d + n) {
1113                 al = SSL_AD_DECODE_ERROR;
1114                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1115                 goto f_err;
1116             }
1117             cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1118
1119             if (cookie_length == 0)
1120                 return 1;
1121         }
1122
1123         /* load the client random */
1124         memcpy(s->s3->client_random, p, SSL3_RANDOM_SIZE);
1125         p += SSL3_RANDOM_SIZE;
1126
1127         /* get the session-id */
1128         j = *(p++);
1129
1130         if (p + j > d + n) {
1131             al = SSL_AD_DECODE_ERROR;
1132             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1133             goto f_err;
1134         }
1135
1136         s->hit = 0;
1137         /*
1138          * Versions before 0.9.7 always allow clients to resume sessions in
1139          * renegotiation. 0.9.7 and later allow this by default, but optionally
1140          * ignore resumption requests with flag
1141          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1142          * than a change to default behavior so that applications relying on
1143          * this for security won't even compile against older library versions).
1144          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to
1145          * request renegotiation but not a new session (s->new_session remains
1146          * unset): for servers, this essentially just means that the
1147          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION setting will be
1148          * ignored.
1149          */
1150         if ((s->new_session
1151              && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION))) {
1152             if (!ssl_get_new_session(s, 1))
1153                 goto err;
1154         } else {
1155             i = ssl_get_prev_session(s, p, j, d + n);
1156             /*
1157              * Only resume if the session's version matches the negotiated
1158              * version.
1159              * RFC 5246 does not provide much useful advice on resumption
1160              * with a different protocol version. It doesn't forbid it but
1161              * the sanity of such behaviour would be questionable.
1162              * In practice, clients do not accept a version mismatch and
1163              * will abort the handshake with an error.
1164              */
1165             if (i == 1 && s->version == s->session->ssl_version) {
1166                 /* previous session */
1167                 s->hit = 1;
1168             } else if (i == -1)
1169                 goto err;
1170             else {
1171                 /* i == 0 */
1172                 if (!ssl_get_new_session(s, 1))
1173                     goto err;
1174             }
1175         }
1176
1177         p += j;
1178
1179         if (SSL_IS_DTLS(s)) {
1180             /* cookie stuff */
1181             if (p + 1 > d + n) {
1182                 al = SSL_AD_DECODE_ERROR;
1183                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1184                 goto f_err;
1185             }
1186             cookie_len = *(p++);
1187
1188             if (p + cookie_len > d + n) {
1189                 al = SSL_AD_DECODE_ERROR;
1190                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1191                 goto f_err;
1192             }
1193
1194             /*
1195              * The ClientHello may contain a cookie even if the
1196              * HelloVerify message has not been sent--make sure that it
1197              * does not cause an overflow.
1198              */
1199             if (cookie_len > sizeof(s->d1->rcvd_cookie)) {
1200                 /* too much data */
1201                 al = SSL_AD_DECODE_ERROR;
1202                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1203                 goto f_err;
1204             }
1205
1206             /* verify the cookie if appropriate option is set. */
1207             if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1208                     && cookie_len > 0) {
1209                 memcpy(s->d1->rcvd_cookie, p, cookie_len);
1210
1211                 if (s->ctx->app_verify_cookie_cb != NULL) {
1212                     if (s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1213                                                      cookie_len) == 0) {
1214                         al = SSL_AD_HANDSHAKE_FAILURE;
1215                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1216                                SSL_R_COOKIE_MISMATCH);
1217                         goto f_err;
1218                     }
1219                     /* else cookie verification succeeded */
1220                 }
1221                 /* default verification */
1222                 else if (memcmp(s->d1->rcvd_cookie, s->d1->cookie,
1223                                 s->d1->cookie_len) != 0) {
1224                     al = SSL_AD_HANDSHAKE_FAILURE;
1225                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1226                     goto f_err;
1227                 }
1228                 /* Set to -2 so if successful we return 2 */
1229                 ret = -2;
1230             }
1231
1232             p += cookie_len;
1233             if (s->method->version == DTLS_ANY_VERSION) {
1234                 /* Select version to use */
1235                 if (s->client_version <= DTLS1_2_VERSION &&
1236                     !(s->options & SSL_OP_NO_DTLSv1_2)) {
1237                     s->version = DTLS1_2_VERSION;
1238                     s->method = DTLSv1_2_server_method();
1239                 } else if (tls1_suiteb(s)) {
1240                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1241                            SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1242                     s->version = s->client_version;
1243                     al = SSL_AD_PROTOCOL_VERSION;
1244                     goto f_err;
1245                 } else if (s->client_version <= DTLS1_VERSION &&
1246                            !(s->options & SSL_OP_NO_DTLSv1)) {
1247                     s->version = DTLS1_VERSION;
1248                     s->method = DTLSv1_server_method();
1249                 } else {
1250                     SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1251                            SSL_R_WRONG_VERSION_NUMBER);
1252                     s->version = s->client_version;
1253                     al = SSL_AD_PROTOCOL_VERSION;
1254                     goto f_err;
1255                 }
1256                 s->session->ssl_version = s->version;
1257             }
1258         }
1259
1260         if (p + 2 > d + n) {
1261             al = SSL_AD_DECODE_ERROR;
1262             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_TOO_SHORT);
1263             goto f_err;
1264         }
1265         n2s(p, i);
1266
1267         if (i == 0) {
1268             al = SSL_AD_ILLEGAL_PARAMETER;
1269             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_CIPHERS_SPECIFIED);
1270             goto f_err;
1271         }
1272
1273         /* i bytes of cipher data + 1 byte for compression length later */
1274         if ((p + i + 1) > (d + n)) {
1275             /* not enough data */
1276             al = SSL_AD_DECODE_ERROR;
1277             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1278             goto f_err;
1279         }
1280         if (ssl_bytes_to_cipher_list(s, p, i, &(ciphers), 0) == NULL) {
1281             goto err;
1282         }
1283         p += i;
1284
1285         /* If it is a hit, check that the cipher is in the list */
1286         if (s->hit) {
1287             j = 0;
1288             id = s->session->cipher->id;
1289
1290 #ifdef CIPHER_DEBUG
1291             fprintf(stderr, "client sent %d ciphers\n",
1292                     sk_SSL_CIPHER_num(ciphers));
1293 #endif
1294             for (i = 0; i < sk_SSL_CIPHER_num(ciphers); i++) {
1295                 c = sk_SSL_CIPHER_value(ciphers, i);
1296 #ifdef CIPHER_DEBUG
1297                 fprintf(stderr, "client [%2d of %2d]:%s\n",
1298                         i, sk_SSL_CIPHER_num(ciphers), SSL_CIPHER_get_name(c));
1299 #endif
1300                 if (c->id == id) {
1301                     j = 1;
1302                     break;
1303                 }
1304             }
1305             /*
1306              * Disabled because it can be used in a ciphersuite downgrade
1307              * attack:
1308              * CVE-2010-4180.
1309              */
1310 #if 0
1311             if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG)
1312                 && (sk_SSL_CIPHER_num(ciphers) == 1)) {
1313                 /*
1314                  * Special case as client bug workaround: the previously used
1315                  * cipher may not be in the current list, the client instead
1316                  * might be trying to continue using a cipher that before wasn't
1317                  * chosen due to server preferences.  We'll have to reject the
1318                  * connection if the cipher is not enabled, though.
1319                  */
1320                 c = sk_SSL_CIPHER_value(ciphers, 0);
1321                 if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0) {
1322                     s->session->cipher = c;
1323                     j = 1;
1324                 }
1325             }
1326 #endif
1327             if (j == 0) {
1328                 /*
1329                  * we need to have the cipher in the cipher list if we are asked
1330                  * to reuse it
1331                  */
1332                 al = SSL_AD_ILLEGAL_PARAMETER;
1333                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1334                        SSL_R_REQUIRED_CIPHER_MISSING);
1335                 goto f_err;
1336             }
1337         }
1338
1339         /* compression */
1340         complen = *(p++);
1341         if ((p + complen) > (d + n)) {
1342             /* not enough data */
1343             al = SSL_AD_DECODE_ERROR;
1344             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_LENGTH_MISMATCH);
1345             goto f_err;
1346         }
1347 #ifndef OPENSSL_NO_COMP
1348         q = p;
1349 #endif
1350         for (j = 0; j < complen; j++) {
1351             if (p[j] == 0)
1352                 break;
1353         }
1354
1355         p += complen;
1356         if (j >= complen) {
1357             /* no compress */
1358             al = SSL_AD_DECODE_ERROR;
1359             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_COMPRESSION_SPECIFIED);
1360             goto f_err;
1361         }
1362     }
1363
1364 #ifndef OPENSSL_NO_TLSEXT
1365     /* TLS extensions */
1366     if (s->version >= SSL3_VERSION) {
1367         if (!ssl_parse_clienthello_tlsext(s, &p, d, n)) {
1368             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_PARSE_TLSEXT);
1369             goto err;
1370         }
1371     }
1372
1373     /*
1374      * Check if we want to use external pre-shared secret for this handshake
1375      * for not reused session only. We need to generate server_random before
1376      * calling tls_session_secret_cb in order to allow SessionTicket
1377      * processing to use it in key derivation.
1378      */
1379     {
1380         unsigned char *pos;
1381         pos = s->s3->server_random;
1382         if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0) {
1383             goto f_err;
1384         }
1385     }
1386
1387     if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb) {
1388         SSL_CIPHER *pref_cipher = NULL;
1389
1390         s->session->master_key_length = sizeof(s->session->master_key);
1391         if (s->tls_session_secret_cb(s, s->session->master_key,
1392                                      &s->session->master_key_length, ciphers,
1393                                      &pref_cipher,
1394                                      s->tls_session_secret_cb_arg)) {
1395             s->hit = 1;
1396             s->session->ciphers = ciphers;
1397             s->session->verify_result = X509_V_OK;
1398
1399             ciphers = NULL;
1400
1401             /* check if some cipher was preferred by call back */
1402             pref_cipher =
1403                 pref_cipher ? pref_cipher : ssl3_choose_cipher(s,
1404                                                                s->
1405                                                                session->ciphers,
1406                                                                SSL_get_ciphers
1407                                                                (s));
1408             if (pref_cipher == NULL) {
1409                 al = SSL_AD_HANDSHAKE_FAILURE;
1410                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1411                 goto f_err;
1412             }
1413
1414             s->session->cipher = pref_cipher;
1415             sk_SSL_CIPHER_free(s->cipher_list);
1416             s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1417             sk_SSL_CIPHER_free(s->cipher_list_by_id);
1418             s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1419         }
1420     }
1421 #endif
1422
1423     /*
1424      * Worst case, we will use the NULL compression, but if we have other
1425      * options, we will now look for them.  We have complen-1 compression
1426      * algorithms from the client, starting at q.
1427      */
1428     s->s3->tmp.new_compression = NULL;
1429 #ifndef OPENSSL_NO_COMP
1430     /* This only happens if we have a cache hit */
1431     if (s->session->compress_meth != 0) {
1432         int m, comp_id = s->session->compress_meth;
1433         /* Perform sanity checks on resumed compression algorithm */
1434         /* Can't disable compression */
1435         if (!ssl_allow_compression(s)) {
1436             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1437                    SSL_R_INCONSISTENT_COMPRESSION);
1438             goto f_err;
1439         }
1440         /* Look for resumed compression method */
1441         for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++) {
1442             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1443             if (comp_id == comp->id) {
1444                 s->s3->tmp.new_compression = comp;
1445                 break;
1446             }
1447         }
1448         if (s->s3->tmp.new_compression == NULL) {
1449             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1450                    SSL_R_INVALID_COMPRESSION_ALGORITHM);
1451             goto f_err;
1452         }
1453         /* Look for resumed method in compression list */
1454         for (m = 0; m < complen; m++) {
1455             if (q[m] == comp_id)
1456                 break;
1457         }
1458         if (m >= complen) {
1459             al = SSL_AD_ILLEGAL_PARAMETER;
1460             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,
1461                    SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1462             goto f_err;
1463         }
1464     } else if (s->hit)
1465         comp = NULL;
1466     else if (ssl_allow_compression(s) && s->ctx->comp_methods) {
1467         /* See if we have a match */
1468         int m, nn, o, v, done = 0;
1469
1470         nn = sk_SSL_COMP_num(s->ctx->comp_methods);
1471         for (m = 0; m < nn; m++) {
1472             comp = sk_SSL_COMP_value(s->ctx->comp_methods, m);
1473             v = comp->id;
1474             for (o = 0; o < complen; o++) {
1475                 if (v == q[o]) {
1476                     done = 1;
1477                     break;
1478                 }
1479             }
1480             if (done)
1481                 break;
1482         }
1483         if (done)
1484             s->s3->tmp.new_compression = comp;
1485         else
1486             comp = NULL;
1487     }
1488 #else
1489     /*
1490      * If compression is disabled we'd better not try to resume a session
1491      * using compression.
1492      */
1493     if (s->session->compress_meth != 0) {
1494         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_INCONSISTENT_COMPRESSION);
1495         goto f_err;
1496     }
1497 #endif
1498
1499     /*
1500      * Given s->session->ciphers and SSL_get_ciphers, we must pick a cipher
1501      */
1502
1503     if (!s->hit) {
1504 #ifdef OPENSSL_NO_COMP
1505         s->session->compress_meth = 0;
1506 #else
1507         s->session->compress_meth = (comp == NULL) ? 0 : comp->id;
1508 #endif
1509         sk_SSL_CIPHER_free(s->session->ciphers);
1510         s->session->ciphers = ciphers;
1511         if (ciphers == NULL) {
1512             al = SSL_AD_INTERNAL_ERROR;
1513             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
1514             goto f_err;
1515         }
1516         ciphers = NULL;
1517         if (!tls1_set_server_sigalgs(s)) {
1518             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1519             goto err;
1520         }
1521         /* Let cert callback update server certificates if required */
1522  retry_cert:
1523         if (s->cert->cert_cb) {
1524             int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1525             if (rv == 0) {
1526                 al = SSL_AD_INTERNAL_ERROR;
1527                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CERT_CB_ERROR);
1528                 goto f_err;
1529             }
1530             if (rv < 0) {
1531                 s->rwstate = SSL_X509_LOOKUP;
1532                 return -1;
1533             }
1534             s->rwstate = SSL_NOTHING;
1535         }
1536         c = ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1537
1538         if (c == NULL) {
1539             al = SSL_AD_HANDSHAKE_FAILURE;
1540             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_NO_SHARED_CIPHER);
1541             goto f_err;
1542         }
1543         s->s3->tmp.new_cipher = c;
1544         /* check whether we should disable session resumption */
1545         if (s->not_resumable_session_cb != NULL)
1546             s->session->not_resumable = s->not_resumable_session_cb(s,
1547                                                                     ((c->algorithm_mkey & (SSL_kDHE | SSL_kECDHE))
1548                                                                      != 0));
1549         if (s->session->not_resumable)
1550             /* do not send a session ticket */
1551             s->tlsext_ticket_expected = 0;
1552     } else {
1553         /* Session-id reuse */
1554         s->s3->tmp.new_cipher = s->session->cipher;
1555     }
1556
1557     if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER)) {
1558         if (!ssl3_digest_cached_records(s))
1559             goto f_err;
1560     }
1561
1562     /*-
1563      * we now have the following setup.
1564      * client_random
1565      * cipher_list          - our prefered list of ciphers
1566      * ciphers              - the clients prefered list of ciphers
1567      * compression          - basically ignored right now
1568      * ssl version is set   - sslv3
1569      * s->session           - The ssl session has been setup.
1570      * s->hit               - session reuse flag
1571      * s->s3->tmp.new_cipher- the new cipher to use.
1572      */
1573
1574     /* Handles TLS extensions that we couldn't check earlier */
1575     if (s->version >= SSL3_VERSION) {
1576         if (ssl_check_clienthello_tlsext_late(s) <= 0) {
1577             SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1578             goto err;
1579         }
1580     }
1581
1582     if (ret < 0)
1583         ret = -ret;
1584     if (0) {
1585  f_err:
1586         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1587  err:
1588         s->state = SSL_ST_ERR;
1589     }
1590
1591     sk_SSL_CIPHER_free(ciphers);
1592     return ret < 0 ? -1 : ret;
1593 }
1594
1595 int ssl3_send_server_hello(SSL *s)
1596 {
1597     unsigned char *buf;
1598     unsigned char *p, *d;
1599     int i, sl;
1600     int al = 0;
1601     unsigned long l;
1602
1603     if (s->state == SSL3_ST_SW_SRVR_HELLO_A) {
1604         buf = (unsigned char *)s->init_buf->data;
1605 #ifdef OPENSSL_NO_TLSEXT
1606         p = s->s3->server_random;
1607         if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0) {
1608             s->state = SSL_ST_ERR;
1609             return -1;
1610         }
1611 #endif
1612         /* Do the message type and length last */
1613         d = p = ssl_handshake_start(s);
1614
1615         *(p++) = s->version >> 8;
1616         *(p++) = s->version & 0xff;
1617
1618         /* Random stuff */
1619         memcpy(p, s->s3->server_random, SSL3_RANDOM_SIZE);
1620         p += SSL3_RANDOM_SIZE;
1621
1622         /*-
1623          * There are several cases for the session ID to send
1624          * back in the server hello:
1625          * - For session reuse from the session cache,
1626          *   we send back the old session ID.
1627          * - If stateless session reuse (using a session ticket)
1628          *   is successful, we send back the client's "session ID"
1629          *   (which doesn't actually identify the session).
1630          * - If it is a new session, we send back the new
1631          *   session ID.
1632          * - However, if we want the new session to be single-use,
1633          *   we send back a 0-length session ID.
1634          * s->hit is non-zero in either case of session reuse,
1635          * so the following won't overwrite an ID that we're supposed
1636          * to send back.
1637          */
1638         if (s->session->not_resumable ||
1639             (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1640              && !s->hit))
1641             s->session->session_id_length = 0;
1642
1643         sl = s->session->session_id_length;
1644         if (sl > (int)sizeof(s->session->session_id)) {
1645             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1646             s->state = SSL_ST_ERR;
1647             return -1;
1648         }
1649         *(p++) = sl;
1650         memcpy(p, s->session->session_id, sl);
1651         p += sl;
1652
1653         /* put the cipher */
1654         i = ssl3_put_cipher_by_char(s->s3->tmp.new_cipher, p);
1655         p += i;
1656
1657         /* put the compression method */
1658 #ifdef OPENSSL_NO_COMP
1659         *(p++) = 0;
1660 #else
1661         if (s->s3->tmp.new_compression == NULL)
1662             *(p++) = 0;
1663         else
1664             *(p++) = s->s3->tmp.new_compression->id;
1665 #endif
1666 #ifndef OPENSSL_NO_TLSEXT
1667         if (ssl_prepare_serverhello_tlsext(s) <= 0) {
1668             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, SSL_R_SERVERHELLO_TLSEXT);
1669             s->state = SSL_ST_ERR;
1670             return -1;
1671         }
1672         if ((p =
1673              ssl_add_serverhello_tlsext(s, p, buf + SSL3_RT_MAX_PLAIN_LENGTH,
1674                                         &al)) == NULL) {
1675             ssl3_send_alert(s, SSL3_AL_FATAL, al);
1676             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1677             s->state = SSL_ST_ERR;
1678             return -1;
1679         }
1680 #endif
1681         /* do the header */
1682         l = (p - d);
1683         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l)) {
1684             SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1685             return -1;
1686         }
1687         s->state = SSL3_ST_SW_SRVR_HELLO_B;
1688     }
1689
1690     /* SSL3_ST_SW_SRVR_HELLO_B */
1691     return ssl_do_write(s);
1692 }
1693
1694 int ssl3_send_server_done(SSL *s)
1695 {
1696
1697     if (s->state == SSL3_ST_SW_SRVR_DONE_A) {
1698         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0)) {
1699             SSLerr(SSL_F_SSL3_SEND_SERVER_DONE, ERR_R_INTERNAL_ERROR);
1700             return -1;
1701         }
1702         s->state = SSL3_ST_SW_SRVR_DONE_B;
1703     }
1704
1705     /* SSL3_ST_SW_SRVR_DONE_B */
1706     return ssl_do_write(s);
1707 }
1708
1709 int ssl3_send_server_key_exchange(SSL *s)
1710 {
1711 #ifndef OPENSSL_NO_RSA
1712     unsigned char *q;
1713     int j, num;
1714     RSA *rsa;
1715     unsigned char md_buf[MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH];
1716     unsigned int u;
1717 #endif
1718 #ifndef OPENSSL_NO_DH
1719     DH *dh = NULL, *dhp;
1720 #endif
1721 #ifndef OPENSSL_NO_EC
1722     EC_KEY *ecdh = NULL, *ecdhp;
1723     unsigned char *encodedPoint = NULL;
1724     int encodedlen = 0;
1725     int curve_id = 0;
1726     BN_CTX *bn_ctx = NULL;
1727 #endif
1728     EVP_PKEY *pkey;
1729     const EVP_MD *md = NULL;
1730     unsigned char *p, *d;
1731     int al, i;
1732     unsigned long type;
1733     int n;
1734     CERT *cert;
1735     BIGNUM *r[4];
1736     int nr[4], kn;
1737     BUF_MEM *buf;
1738     EVP_MD_CTX md_ctx;
1739
1740     EVP_MD_CTX_init(&md_ctx);
1741     if (s->state == SSL3_ST_SW_KEY_EXCH_A) {
1742         type = s->s3->tmp.new_cipher->algorithm_mkey;
1743         cert = s->cert;
1744
1745         buf = s->init_buf;
1746
1747         r[0] = r[1] = r[2] = r[3] = NULL;
1748         n = 0;
1749 #ifndef OPENSSL_NO_RSA
1750         if (type & SSL_kRSA) {
1751             rsa = cert->rsa_tmp;
1752             if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL)) {
1753                 rsa = s->cert->rsa_tmp_cb(s,
1754                                           SSL_C_IS_EXPORT(s->s3->
1755                                                           tmp.new_cipher),
1756                                           SSL_C_EXPORT_PKEYLENGTH(s->s3->
1757                                                                   tmp.new_cipher));
1758                 if (rsa == NULL) {
1759                     al = SSL_AD_HANDSHAKE_FAILURE;
1760                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1761                            SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1762                     goto f_err;
1763                 }
1764                 RSA_up_ref(rsa);
1765                 cert->rsa_tmp = rsa;
1766             }
1767             if (rsa == NULL) {
1768                 al = SSL_AD_HANDSHAKE_FAILURE;
1769                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1770                        SSL_R_MISSING_TMP_RSA_KEY);
1771                 goto f_err;
1772             }
1773             r[0] = rsa->n;
1774             r[1] = rsa->e;
1775             s->s3->tmp.use_rsa_tmp = 1;
1776         } else
1777 #endif
1778 #ifndef OPENSSL_NO_DH
1779         if (type & SSL_kDHE) {
1780             if (s->cert->dh_tmp_auto) {
1781                 dhp = ssl_get_auto_dh(s);
1782                 if (dhp == NULL) {
1783                     al = SSL_AD_INTERNAL_ERROR;
1784                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1785                            ERR_R_INTERNAL_ERROR);
1786                     goto f_err;
1787                 }
1788             } else
1789                 dhp = cert->dh_tmp;
1790             if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1791                 dhp = s->cert->dh_tmp_cb(s,
1792                                          SSL_C_IS_EXPORT(s->s3->
1793                                                          tmp.new_cipher),
1794                                          SSL_C_EXPORT_PKEYLENGTH(s->s3->
1795                                                                  tmp.new_cipher));
1796             if (dhp == NULL) {
1797                 al = SSL_AD_HANDSHAKE_FAILURE;
1798                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1799                        SSL_R_MISSING_TMP_DH_KEY);
1800                 goto f_err;
1801             }
1802             if (!ssl_security(s, SSL_SECOP_TMP_DH,
1803                               DH_security_bits(dhp), 0, dhp)) {
1804                 al = SSL_AD_HANDSHAKE_FAILURE;
1805                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1806                        SSL_R_DH_KEY_TOO_SMALL);
1807                 goto f_err;
1808             }
1809             if (s->s3->tmp.dh != NULL) {
1810                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1811                        ERR_R_INTERNAL_ERROR);
1812                 goto err;
1813             }
1814
1815             if (s->cert->dh_tmp_auto)
1816                 dh = dhp;
1817             else if ((dh = DHparams_dup(dhp)) == NULL) {
1818                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1819                 goto err;
1820             }
1821
1822             s->s3->tmp.dh = dh;
1823             if ((dhp->pub_key == NULL ||
1824                  dhp->priv_key == NULL ||
1825                  (s->options & SSL_OP_SINGLE_DH_USE))) {
1826                 if (!DH_generate_key(dh)) {
1827                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1828                     goto err;
1829                 }
1830             } else {
1831                 dh->pub_key = BN_dup(dhp->pub_key);
1832                 dh->priv_key = BN_dup(dhp->priv_key);
1833                 if ((dh->pub_key == NULL) || (dh->priv_key == NULL)) {
1834                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_DH_LIB);
1835                     goto err;
1836                 }
1837             }
1838             r[0] = dh->p;
1839             r[1] = dh->g;
1840             r[2] = dh->pub_key;
1841         } else
1842 #endif
1843 #ifndef OPENSSL_NO_EC
1844         if (type & SSL_kECDHE) {
1845             const EC_GROUP *group;
1846
1847             ecdhp = cert->ecdh_tmp;
1848             if (s->cert->ecdh_tmp_auto) {
1849                 /* Get NID of appropriate shared curve */
1850                 int nid = tls1_shared_curve(s, -2);
1851                 if (nid != NID_undef)
1852                     ecdhp = EC_KEY_new_by_curve_name(nid);
1853             } else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb) {
1854                 ecdhp = s->cert->ecdh_tmp_cb(s,
1855                                              SSL_C_IS_EXPORT(s->s3->
1856                                                              tmp.new_cipher),
1857                                              SSL_C_EXPORT_PKEYLENGTH(s->
1858                                                                      s3->tmp.new_cipher));
1859             }
1860             if (ecdhp == NULL) {
1861                 al = SSL_AD_HANDSHAKE_FAILURE;
1862                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1863                        SSL_R_MISSING_TMP_ECDH_KEY);
1864                 goto f_err;
1865             }
1866
1867             if (s->s3->tmp.ecdh != NULL) {
1868                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1869                        ERR_R_INTERNAL_ERROR);
1870                 goto err;
1871             }
1872
1873             /* Duplicate the ECDH structure. */
1874             if (ecdhp == NULL) {
1875                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1876                 goto err;
1877             }
1878             if (s->cert->ecdh_tmp_auto)
1879                 ecdh = ecdhp;
1880             else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL) {
1881                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1882                 goto err;
1883             }
1884
1885             s->s3->tmp.ecdh = ecdh;
1886             if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1887                 (EC_KEY_get0_private_key(ecdh) == NULL) ||
1888                 (s->options & SSL_OP_SINGLE_ECDH_USE)) {
1889                 if (!EC_KEY_generate_key(ecdh)) {
1890                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1891                            ERR_R_ECDH_LIB);
1892                     goto err;
1893                 }
1894             }
1895
1896             if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1897                 (EC_KEY_get0_public_key(ecdh) == NULL) ||
1898                 (EC_KEY_get0_private_key(ecdh) == NULL)) {
1899                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1900                 goto err;
1901             }
1902
1903             if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1904                 (EC_GROUP_get_degree(group) > 163)) {
1905                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1906                        SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1907                 goto err;
1908             }
1909
1910             /*
1911              * XXX: For now, we only support ephemeral ECDH keys over named
1912              * (not generic) curves. For supported named curves, curve_id is
1913              * non-zero.
1914              */
1915             if ((curve_id =
1916                  tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1917                 == 0) {
1918                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1919                        SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1920                 goto err;
1921             }
1922
1923             /*
1924              * Encode the public key. First check the size of encoding and
1925              * allocate memory accordingly.
1926              */
1927             encodedlen = EC_POINT_point2oct(group,
1928                                             EC_KEY_get0_public_key(ecdh),
1929                                             POINT_CONVERSION_UNCOMPRESSED,
1930                                             NULL, 0, NULL);
1931
1932             encodedPoint = (unsigned char *)
1933                 OPENSSL_malloc(encodedlen * sizeof(unsigned char));
1934             bn_ctx = BN_CTX_new();
1935             if ((encodedPoint == NULL) || (bn_ctx == NULL)) {
1936                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1937                        ERR_R_MALLOC_FAILURE);
1938                 goto err;
1939             }
1940
1941             encodedlen = EC_POINT_point2oct(group,
1942                                             EC_KEY_get0_public_key(ecdh),
1943                                             POINT_CONVERSION_UNCOMPRESSED,
1944                                             encodedPoint, encodedlen, bn_ctx);
1945
1946             if (encodedlen == 0) {
1947                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_ECDH_LIB);
1948                 goto err;
1949             }
1950
1951             BN_CTX_free(bn_ctx);
1952             bn_ctx = NULL;
1953
1954             /*
1955              * XXX: For now, we only support named (not generic) curves in
1956              * ECDH ephemeral key exchanges. In this situation, we need four
1957              * additional bytes to encode the entire ServerECDHParams
1958              * structure.
1959              */
1960             n = 4 + encodedlen;
1961
1962             /*
1963              * We'll generate the serverKeyExchange message explicitly so we
1964              * can set these to NULLs
1965              */
1966             r[0] = NULL;
1967             r[1] = NULL;
1968             r[2] = NULL;
1969             r[3] = NULL;
1970         } else
1971 #endif                          /* !OPENSSL_NO_EC */
1972 #ifndef OPENSSL_NO_PSK
1973         if (type & SSL_kPSK) {
1974             /*
1975              * reserve size for record length and PSK identity hint
1976              */
1977             n += 2 + strlen(s->ctx->psk_identity_hint);
1978         } else
1979 #endif                          /* !OPENSSL_NO_PSK */
1980 #ifndef OPENSSL_NO_SRP
1981         if (type & SSL_kSRP) {
1982             if ((s->srp_ctx.N == NULL) ||
1983                 (s->srp_ctx.g == NULL) ||
1984                 (s->srp_ctx.s == NULL) || (s->srp_ctx.B == NULL)) {
1985                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1986                        SSL_R_MISSING_SRP_PARAM);
1987                 goto err;
1988             }
1989             r[0] = s->srp_ctx.N;
1990             r[1] = s->srp_ctx.g;
1991             r[2] = s->srp_ctx.s;
1992             r[3] = s->srp_ctx.B;
1993         } else
1994 #endif
1995         {
1996             al = SSL_AD_HANDSHAKE_FAILURE;
1997             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1998                    SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1999             goto f_err;
2000         }
2001         for (i = 0; i < 4 && r[i] != NULL; i++) {
2002             nr[i] = BN_num_bytes(r[i]);
2003 #ifndef OPENSSL_NO_SRP
2004             if ((i == 2) && (type & SSL_kSRP))
2005                 n += 1 + nr[i];
2006             else
2007 #endif
2008                 n += 2 + nr[i];
2009         }
2010
2011         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL | SSL_aSRP))
2012             && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)) {
2013             if ((pkey = ssl_get_sign_pkey(s, s->s3->tmp.new_cipher, &md))
2014                 == NULL) {
2015                 al = SSL_AD_DECODE_ERROR;
2016                 goto f_err;
2017             }
2018             kn = EVP_PKEY_size(pkey);
2019         } else {
2020             pkey = NULL;
2021             kn = 0;
2022         }
2023
2024         if (!BUF_MEM_grow_clean(buf, n + SSL_HM_HEADER_LENGTH(s) + kn)) {
2025             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_BUF);
2026             goto err;
2027         }
2028         d = p = ssl_handshake_start(s);
2029
2030         for (i = 0; i < 4 && r[i] != NULL; i++) {
2031 #ifndef OPENSSL_NO_SRP
2032             if ((i == 2) && (type & SSL_kSRP)) {
2033                 *p = nr[i];
2034                 p++;
2035             } else
2036 #endif
2037                 s2n(nr[i], p);
2038             BN_bn2bin(r[i], p);
2039             p += nr[i];
2040         }
2041
2042 #ifndef OPENSSL_NO_EC
2043         if (type & SSL_kECDHE) {
2044             /*
2045              * XXX: For now, we only support named (not generic) curves. In
2046              * this situation, the serverKeyExchange message has: [1 byte
2047              * CurveType], [2 byte CurveName] [1 byte length of encoded
2048              * point], followed by the actual encoded point itself
2049              */
2050             *p = NAMED_CURVE_TYPE;
2051             p += 1;
2052             *p = 0;
2053             p += 1;
2054             *p = curve_id;
2055             p += 1;
2056             *p = encodedlen;
2057             p += 1;
2058             memcpy(p, encodedPoint, encodedlen);
2059             OPENSSL_free(encodedPoint);
2060             encodedPoint = NULL;
2061             p += encodedlen;
2062         }
2063 #endif
2064
2065 #ifndef OPENSSL_NO_PSK
2066         if (type & SSL_kPSK) {
2067             /* copy PSK identity hint */
2068             s2n(strlen(s->ctx->psk_identity_hint), p);
2069             strncpy((char *)p, s->ctx->psk_identity_hint,
2070                     strlen(s->ctx->psk_identity_hint));
2071             p += strlen(s->ctx->psk_identity_hint);
2072         }
2073 #endif
2074
2075         /* not anonymous */
2076         if (pkey != NULL) {
2077             /*
2078              * n is the length of the params, they start at &(d[4]) and p
2079              * points to the space at the end.
2080              */
2081 #ifndef OPENSSL_NO_RSA
2082             if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s)) {
2083                 q = md_buf;
2084                 j = 0;
2085                 for (num = 2; num > 0; num--) {
2086                     EVP_MD_CTX_set_flags(&md_ctx,
2087                                          EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2088                     EVP_DigestInit_ex(&md_ctx, (num == 2)
2089                                       ? s->ctx->md5 : s->ctx->sha1, NULL);
2090                     EVP_DigestUpdate(&md_ctx, &(s->s3->client_random[0]),
2091                                      SSL3_RANDOM_SIZE);
2092                     EVP_DigestUpdate(&md_ctx, &(s->s3->server_random[0]),
2093                                      SSL3_RANDOM_SIZE);
2094                     EVP_DigestUpdate(&md_ctx, d, n);
2095                     EVP_DigestFinal_ex(&md_ctx, q, (unsigned int *)&i);
2096                     q += i;
2097                     j += i;
2098                 }
2099                 if (RSA_sign(NID_md5_sha1, md_buf, j,
2100                              &(p[2]), &u, pkey->pkey.rsa) <= 0) {
2101                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_RSA);
2102                     goto err;
2103                 }
2104                 s2n(u, p);
2105                 n += u + 2;
2106             } else
2107 #endif
2108             if (md) {
2109                 /* send signature algorithm */
2110                 if (SSL_USE_SIGALGS(s)) {
2111                     if (!tls12_get_sigandhash(p, pkey, md)) {
2112                         /* Should never happen */
2113                         al = SSL_AD_INTERNAL_ERROR;
2114                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2115                                ERR_R_INTERNAL_ERROR);
2116                         goto f_err;
2117                     }
2118                     p += 2;
2119                 }
2120 #ifdef SSL_DEBUG
2121                 fprintf(stderr, "Using hash %s\n", EVP_MD_name(md));
2122 #endif
2123                 EVP_SignInit_ex(&md_ctx, md, NULL);
2124                 EVP_SignUpdate(&md_ctx, &(s->s3->client_random[0]),
2125                                SSL3_RANDOM_SIZE);
2126                 EVP_SignUpdate(&md_ctx, &(s->s3->server_random[0]),
2127                                SSL3_RANDOM_SIZE);
2128                 EVP_SignUpdate(&md_ctx, d, n);
2129                 if (!EVP_SignFinal(&md_ctx, &(p[2]),
2130                                    (unsigned int *)&i, pkey)) {
2131                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_LIB_EVP);
2132                     goto err;
2133                 }
2134                 s2n(i, p);
2135                 n += i + 2;
2136                 if (SSL_USE_SIGALGS(s))
2137                     n += 2;
2138             } else {
2139                 /* Is this error check actually needed? */
2140                 al = SSL_AD_HANDSHAKE_FAILURE;
2141                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
2142                        SSL_R_UNKNOWN_PKEY_TYPE);
2143                 goto f_err;
2144             }
2145         }
2146
2147         if (!ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n)) {
2148             al = SSL_AD_HANDSHAKE_FAILURE;
2149             SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2150             goto f_err;
2151         }
2152     }
2153
2154     s->state = SSL3_ST_SW_KEY_EXCH_B;
2155     EVP_MD_CTX_cleanup(&md_ctx);
2156     return ssl_do_write(s);
2157  f_err:
2158     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2159  err:
2160 #ifndef OPENSSL_NO_EC
2161     OPENSSL_free(encodedPoint);
2162     BN_CTX_free(bn_ctx);
2163 #endif
2164     EVP_MD_CTX_cleanup(&md_ctx);
2165     s->state = SSL_ST_ERR;
2166     return (-1);
2167 }
2168
2169 int ssl3_send_certificate_request(SSL *s)
2170 {
2171     unsigned char *p, *d;
2172     int i, j, nl, off, n;
2173     STACK_OF(X509_NAME) *sk = NULL;
2174     X509_NAME *name;
2175     BUF_MEM *buf;
2176
2177     if (s->state == SSL3_ST_SW_CERT_REQ_A) {
2178         buf = s->init_buf;
2179
2180         d = p = ssl_handshake_start(s);
2181
2182         /* get the list of acceptable cert types */
2183         p++;
2184         n = ssl3_get_req_cert_type(s, p);
2185         d[0] = n;
2186         p += n;
2187         n++;
2188
2189         if (SSL_USE_SIGALGS(s)) {
2190             const unsigned char *psigs;
2191             unsigned char *etmp = p;
2192             nl = tls12_get_psigalgs(s, &psigs);
2193             /* Skip over length for now */
2194             p += 2;
2195             nl = tls12_copy_sigalgs(s, p, psigs, nl);
2196             /* Now fill in length */
2197             s2n(nl, etmp);
2198             p += nl;
2199             n += nl + 2;
2200         }
2201
2202         off = n;
2203         p += 2;
2204         n += 2;
2205
2206         sk = SSL_get_client_CA_list(s);
2207         nl = 0;
2208         if (sk != NULL) {
2209             for (i = 0; i < sk_X509_NAME_num(sk); i++) {
2210                 name = sk_X509_NAME_value(sk, i);
2211                 j = i2d_X509_NAME(name, NULL);
2212                 if (!BUF_MEM_grow_clean
2213                     (buf, SSL_HM_HEADER_LENGTH(s) + n + j + 2)) {
2214                     SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,
2215                            ERR_R_BUF_LIB);
2216                     goto err;
2217                 }
2218                 p = ssl_handshake_start(s) + n;
2219                 s2n(j, p);
2220                 i2d_X509_NAME(name, &p);
2221                 n += 2 + j;
2222                 nl += 2 + j;
2223             }
2224         }
2225         /* else no CA names */
2226         p = ssl_handshake_start(s) + off;
2227         s2n(nl, p);
2228
2229         if (!ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n)) {
2230             SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST, ERR_R_INTERNAL_ERROR);
2231             return -1;
2232         }
2233
2234         s->state = SSL3_ST_SW_CERT_REQ_B;
2235     }
2236
2237     /* SSL3_ST_SW_CERT_REQ_B */
2238     return ssl_do_write(s);
2239  err:
2240     s->state = SSL_ST_ERR;
2241     return (-1);
2242 }
2243
2244 int ssl3_get_client_key_exchange(SSL *s)
2245 {
2246     int i, al, ok;
2247     long n;
2248     unsigned long alg_k;
2249     unsigned char *p;
2250 #ifndef OPENSSL_NO_RSA
2251     RSA *rsa = NULL;
2252     EVP_PKEY *pkey = NULL;
2253 #endif
2254 #ifndef OPENSSL_NO_DH
2255     BIGNUM *pub = NULL;
2256     DH *dh_srvr, *dh_clnt = NULL;
2257 #endif
2258
2259 #ifndef OPENSSL_NO_EC
2260     EC_KEY *srvr_ecdh = NULL;
2261     EVP_PKEY *clnt_pub_pkey = NULL;
2262     EC_POINT *clnt_ecpoint = NULL;
2263     BN_CTX *bn_ctx = NULL;
2264 #endif
2265
2266     n = s->method->ssl_get_message(s,
2267                                    SSL3_ST_SR_KEY_EXCH_A,
2268                                    SSL3_ST_SR_KEY_EXCH_B,
2269                                    SSL3_MT_CLIENT_KEY_EXCHANGE, 2048, &ok);
2270
2271     if (!ok)
2272         return ((int)n);
2273     p = (unsigned char *)s->init_msg;
2274
2275     alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
2276
2277 #ifndef OPENSSL_NO_RSA
2278     if (alg_k & SSL_kRSA) {
2279         unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2280         int decrypt_len;
2281         unsigned char decrypt_good, version_good;
2282         size_t j;
2283
2284         /* FIX THIS UP EAY EAY EAY EAY */
2285         if (s->s3->tmp.use_rsa_tmp) {
2286             if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2287                 rsa = s->cert->rsa_tmp;
2288             /*
2289              * Don't do a callback because rsa_tmp should be sent already
2290              */
2291             if (rsa == NULL) {
2292                 al = SSL_AD_HANDSHAKE_FAILURE;
2293                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2294                        SSL_R_MISSING_TMP_RSA_PKEY);
2295                 goto f_err;
2296
2297             }
2298         } else {
2299             pkey = s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2300             if ((pkey == NULL) ||
2301                 (pkey->type != EVP_PKEY_RSA) || (pkey->pkey.rsa == NULL)) {
2302                 al = SSL_AD_HANDSHAKE_FAILURE;
2303                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2304                        SSL_R_MISSING_RSA_CERTIFICATE);
2305                 goto f_err;
2306             }
2307             rsa = pkey->pkey.rsa;
2308         }
2309
2310         /* TLS and [incidentally] DTLS{0xFEFF} */
2311         if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER) {
2312             n2s(p, i);
2313             if (n != i + 2) {
2314                 if (!(s->options & SSL_OP_TLS_D5_BUG)) {
2315                     al = SSL_AD_DECODE_ERROR;
2316                     SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2317                            SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2318                     goto f_err;
2319                 } else
2320                     p -= 2;
2321             } else
2322                 n = i;
2323         }
2324
2325         /*
2326          * Reject overly short RSA ciphertext because we want to be sure
2327          * that the buffer size makes it safe to iterate over the entire
2328          * size of a premaster secret (SSL_MAX_MASTER_KEY_LENGTH). The
2329          * actual expected size is larger due to RSA padding, but the
2330          * bound is sufficient to be safe.
2331          */
2332         if (n < SSL_MAX_MASTER_KEY_LENGTH) {
2333             al = SSL_AD_DECRYPT_ERROR;
2334             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2335                    SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2336             goto f_err;
2337         }
2338
2339         /*
2340          * We must not leak whether a decryption failure occurs because of
2341          * Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see RFC 2246,
2342          * section 7.4.7.1). The code follows that advice of the TLS RFC and
2343          * generates a random premaster secret for the case that the decrypt
2344          * fails. See https://tools.ietf.org/html/rfc5246#section-7.4.7.1
2345          */
2346
2347         if (RAND_bytes(rand_premaster_secret,
2348                               sizeof(rand_premaster_secret)) <= 0)
2349             goto err;
2350         decrypt_len =
2351             RSA_private_decrypt((int)n, p, p, rsa, RSA_PKCS1_PADDING);
2352         ERR_clear_error();
2353
2354         /*
2355          * decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH. decrypt_good will
2356          * be 0xff if so and zero otherwise.
2357          */
2358         decrypt_good =
2359             constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2360
2361         /*
2362          * If the version in the decrypted pre-master secret is correct then
2363          * version_good will be 0xff, otherwise it'll be zero. The
2364          * Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2365          * (http://eprint.iacr.org/2003/052/) exploits the version number
2366          * check as a "bad version oracle". Thus version checks are done in
2367          * constant time and are treated like any other decryption error.
2368          */
2369         version_good =
2370             constant_time_eq_8(p[0], (unsigned)(s->client_version >> 8));
2371         version_good &=
2372             constant_time_eq_8(p[1], (unsigned)(s->client_version & 0xff));
2373
2374         /*
2375          * The premaster secret must contain the same version number as the
2376          * ClientHello to detect version rollback attacks (strangely, the
2377          * protocol does not offer such protection for DH ciphersuites).
2378          * However, buggy clients exist that send the negotiated protocol
2379          * version instead if the server does not support the requested
2380          * protocol version. If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such
2381          * clients.
2382          */
2383         if (s->options & SSL_OP_TLS_ROLLBACK_BUG) {
2384             unsigned char workaround_good;
2385             workaround_good =
2386                 constant_time_eq_8(p[0], (unsigned)(s->version >> 8));
2387             workaround_good &=
2388                 constant_time_eq_8(p[1], (unsigned)(s->version & 0xff));
2389             version_good |= workaround_good;
2390         }
2391
2392         /*
2393          * Both decryption and version must be good for decrypt_good to
2394          * remain non-zero (0xff).
2395          */
2396         decrypt_good &= version_good;
2397
2398         /*
2399          * Now copy rand_premaster_secret over from p using
2400          * decrypt_good_mask. If decryption failed, then p does not
2401          * contain valid plaintext, however, a check above guarantees
2402          * it is still sufficiently large to read from.
2403          */
2404         for (j = 0; j < sizeof(rand_premaster_secret); j++) {
2405             p[j] = constant_time_select_8(decrypt_good, p[j],
2406                                           rand_premaster_secret[j]);
2407         }
2408
2409         s->session->master_key_length =
2410             s->method->ssl3_enc->generate_master_secret(s,
2411                                                         s->
2412                                                         session->master_key,
2413                                                         p,
2414                                                         sizeof
2415                                                         (rand_premaster_secret));
2416         OPENSSL_cleanse(p, sizeof(rand_premaster_secret));
2417         if (s->session->master_key_length < 0) {
2418             al = SSL_AD_INTERNAL_ERROR;
2419             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2420             goto f_err;
2421         }
2422     } else
2423 #endif
2424 #ifndef OPENSSL_NO_DH
2425     if (alg_k & (SSL_kDHE | SSL_kDHr | SSL_kDHd)) {
2426         int idx = -1;
2427         EVP_PKEY *skey = NULL;
2428         if (n > 1) {
2429             n2s(p, i);
2430         } else {
2431             if (alg_k & SSL_kDHE) {
2432                 al = SSL_AD_HANDSHAKE_FAILURE;
2433                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2434                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2435                 goto f_err;
2436             }
2437             i = 0;
2438         }
2439         if (n && n != i + 2) {
2440             if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG)) {
2441                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2442                        SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2443                 goto err;
2444             } else {
2445                 p -= 2;
2446                 i = (int)n;
2447             }
2448         }
2449         if (alg_k & SSL_kDHr)
2450             idx = SSL_PKEY_DH_RSA;
2451         else if (alg_k & SSL_kDHd)
2452             idx = SSL_PKEY_DH_DSA;
2453         if (idx >= 0) {
2454             skey = s->cert->pkeys[idx].privatekey;
2455             if ((skey == NULL) ||
2456                 (skey->type != EVP_PKEY_DH) || (skey->pkey.dh == NULL)) {
2457                 al = SSL_AD_HANDSHAKE_FAILURE;
2458                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2459                        SSL_R_MISSING_RSA_CERTIFICATE);
2460                 goto f_err;
2461             }
2462             dh_srvr = skey->pkey.dh;
2463         } else if (s->s3->tmp.dh == NULL) {
2464             al = SSL_AD_HANDSHAKE_FAILURE;
2465             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2466                    SSL_R_MISSING_TMP_DH_KEY);
2467             goto f_err;
2468         } else
2469             dh_srvr = s->s3->tmp.dh;
2470
2471         if (n == 0L) {
2472             /* Get pubkey from cert */
2473             EVP_PKEY *clkey = X509_get_pubkey(s->session->peer);
2474             if (clkey) {
2475                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2476                     dh_clnt = EVP_PKEY_get1_DH(clkey);
2477             }
2478             if (dh_clnt == NULL) {
2479                 al = SSL_AD_HANDSHAKE_FAILURE;
2480                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2481                        SSL_R_MISSING_TMP_DH_KEY);
2482                 goto f_err;
2483             }
2484             EVP_PKEY_free(clkey);
2485             pub = dh_clnt->pub_key;
2486         } else
2487             pub = BN_bin2bn(p, i, NULL);
2488         if (pub == NULL) {
2489             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_BN_LIB);
2490             goto err;
2491         }
2492
2493         i = DH_compute_key(p, pub, dh_srvr);
2494
2495         if (i <= 0) {
2496             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_DH_LIB);
2497             BN_clear_free(pub);
2498             goto err;
2499         }
2500
2501         DH_free(s->s3->tmp.dh);
2502         s->s3->tmp.dh = NULL;
2503         if (dh_clnt)
2504             DH_free(dh_clnt);
2505         else
2506             BN_clear_free(pub);
2507         pub = NULL;
2508         s->session->master_key_length =
2509             s->method->ssl3_enc->generate_master_secret(s,
2510                                                         s->
2511                                                         session->master_key,
2512                                                         p, i);
2513         OPENSSL_cleanse(p, i);
2514         if (s->session->master_key_length < 0) {
2515             al = SSL_AD_INTERNAL_ERROR;
2516             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2517             goto f_err;
2518         }
2519         if (dh_clnt)
2520             return 2;
2521     } else
2522 #endif
2523
2524 #ifndef OPENSSL_NO_EC
2525     if (alg_k & (SSL_kECDHE | SSL_kECDHr | SSL_kECDHe)) {
2526         int ret = 1;
2527         int field_size = 0;
2528         const EC_KEY *tkey;
2529         const EC_GROUP *group;
2530         const BIGNUM *priv_key;
2531
2532         /* initialize structures for server's ECDH key pair */
2533         if ((srvr_ecdh = EC_KEY_new()) == NULL) {
2534             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2535             goto err;
2536         }
2537
2538         /* Let's get server private key and group information */
2539         if (alg_k & (SSL_kECDHr | SSL_kECDHe)) {
2540             /* use the certificate */
2541             tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2542         } else {
2543             /*
2544              * use the ephermeral values we saved when generating the
2545              * ServerKeyExchange msg.
2546              */
2547             tkey = s->s3->tmp.ecdh;
2548         }
2549
2550         group = EC_KEY_get0_group(tkey);
2551         priv_key = EC_KEY_get0_private_key(tkey);
2552
2553         if (!EC_KEY_set_group(srvr_ecdh, group) ||
2554             !EC_KEY_set_private_key(srvr_ecdh, priv_key)) {
2555             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2556             goto err;
2557         }
2558
2559         /* Let's get client's public key */
2560         if ((clnt_ecpoint = EC_POINT_new(group)) == NULL) {
2561             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2562             goto err;
2563         }
2564
2565         if (n == 0L) {
2566             /* Client Publickey was in Client Certificate */
2567
2568             if (alg_k & SSL_kECDHE) {
2569                 al = SSL_AD_HANDSHAKE_FAILURE;
2570                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2571                        SSL_R_MISSING_TMP_ECDH_KEY);
2572                 goto f_err;
2573             }
2574             if (((clnt_pub_pkey = X509_get_pubkey(s->session->peer))
2575                  == NULL) || (clnt_pub_pkey->type != EVP_PKEY_EC)) {
2576                 /*
2577                  * XXX: For now, we do not support client authentication
2578                  * using ECDH certificates so this branch (n == 0L) of the
2579                  * code is never executed. When that support is added, we
2580                  * ought to ensure the key received in the certificate is
2581                  * authorized for key agreement. ECDH_compute_key implicitly
2582                  * checks that the two ECDH shares are for the same group.
2583                  */
2584                 al = SSL_AD_HANDSHAKE_FAILURE;
2585                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2586                        SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2587                 goto f_err;
2588             }
2589
2590             if (EC_POINT_copy(clnt_ecpoint,
2591                               EC_KEY_get0_public_key(clnt_pub_pkey->
2592                                                      pkey.ec)) == 0) {
2593                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2594                 goto err;
2595             }
2596             ret = 2;            /* Skip certificate verify processing */
2597         } else {
2598             /*
2599              * Get client's public key from encoded point in the
2600              * ClientKeyExchange message.
2601              */
2602             if ((bn_ctx = BN_CTX_new()) == NULL) {
2603                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2604                        ERR_R_MALLOC_FAILURE);
2605                 goto err;
2606             }
2607
2608             /* Get encoded point length */
2609             i = *p;
2610             p += 1;
2611             if (n != 1 + i) {
2612                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2613                 goto err;
2614             }
2615             if (EC_POINT_oct2point(group, clnt_ecpoint, p, i, bn_ctx) == 0) {
2616                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_EC_LIB);
2617                 goto err;
2618             }
2619             /*
2620              * p is pointing to somewhere in the buffer currently, so set it
2621              * to the start
2622              */
2623             p = (unsigned char *)s->init_buf->data;
2624         }
2625
2626         /* Compute the shared pre-master secret */
2627         field_size = EC_GROUP_get_degree(group);
2628         if (field_size <= 0) {
2629             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2630             goto err;
2631         }
2632         i = ECDH_compute_key(p, (field_size + 7) / 8, clnt_ecpoint, srvr_ecdh,
2633                              NULL);
2634         if (i <= 0) {
2635             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2636             goto err;
2637         }
2638
2639         EVP_PKEY_free(clnt_pub_pkey);
2640         EC_POINT_free(clnt_ecpoint);
2641         EC_KEY_free(srvr_ecdh);
2642         BN_CTX_free(bn_ctx);
2643         EC_KEY_free(s->s3->tmp.ecdh);
2644         s->s3->tmp.ecdh = NULL;
2645
2646         /* Compute the master secret */
2647         s->session->master_key_length =
2648             s->method->ssl3_enc->generate_master_secret(s,
2649                                                         s->
2650                                                         session->master_key,
2651                                                         p, i);
2652
2653         OPENSSL_cleanse(p, i);
2654         if (s->session->master_key_length < 0) {
2655             al = SSL_AD_INTERNAL_ERROR;
2656             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2657             goto f_err;
2658         }
2659         return (ret);
2660     } else
2661 #endif
2662 #ifndef OPENSSL_NO_PSK
2663     if (alg_k & SSL_kPSK) {
2664         unsigned char *t = NULL;
2665         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN * 2 + 4];
2666         unsigned int pre_ms_len = 0, psk_len = 0;
2667         int psk_err = 1;
2668         char tmp_id[PSK_MAX_IDENTITY_LEN + 1];
2669
2670         al = SSL_AD_HANDSHAKE_FAILURE;
2671
2672         n2s(p, i);
2673         if (n != i + 2) {
2674             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_LENGTH_MISMATCH);
2675             goto psk_err;
2676         }
2677         if (i > PSK_MAX_IDENTITY_LEN) {
2678             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2679                    SSL_R_DATA_LENGTH_TOO_LONG);
2680             goto psk_err;
2681         }
2682         if (s->psk_server_callback == NULL) {
2683             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2684                    SSL_R_PSK_NO_SERVER_CB);
2685             goto psk_err;
2686         }
2687
2688         /*
2689          * Create guaranteed NULL-terminated identity string for the callback
2690          */
2691         memcpy(tmp_id, p, i);
2692         memset(tmp_id + i, 0, PSK_MAX_IDENTITY_LEN + 1 - i);
2693         psk_len = s->psk_server_callback(s, tmp_id,
2694                                          psk_or_pre_ms,
2695                                          sizeof(psk_or_pre_ms));
2696         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN + 1);
2697
2698         if (psk_len > PSK_MAX_PSK_LEN) {
2699             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2700             goto psk_err;
2701         } else if (psk_len == 0) {
2702             /*
2703              * PSK related to the given identity not found
2704              */
2705             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2706                    SSL_R_PSK_IDENTITY_NOT_FOUND);
2707             al = SSL_AD_UNKNOWN_PSK_IDENTITY;
2708             goto psk_err;
2709         }
2710
2711         /* create PSK pre_master_secret */
2712         pre_ms_len = 2 + psk_len + 2 + psk_len;
2713         t = psk_or_pre_ms;
2714         memmove(psk_or_pre_ms + psk_len + 4, psk_or_pre_ms, psk_len);
2715         s2n(psk_len, t);
2716         memset(t, 0, psk_len);
2717         t += psk_len;
2718         s2n(psk_len, t);
2719
2720         OPENSSL_free(s->session->psk_identity);
2721         s->session->psk_identity = BUF_strdup((char *)p);
2722         if (s->session->psk_identity == NULL) {
2723             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2724             goto psk_err;
2725         }
2726
2727         OPENSSL_free(s->session->psk_identity_hint);
2728         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2729         if (s->ctx->psk_identity_hint != NULL &&
2730             s->session->psk_identity_hint == NULL) {
2731             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2732             goto psk_err;
2733         }
2734
2735         s->session->master_key_length =
2736             s->method->ssl3_enc->generate_master_secret(s,
2737                                                         s->
2738                                                         session->master_key,
2739                                                         psk_or_pre_ms,
2740                                                         pre_ms_len);
2741         if (s->session->master_key_length < 0) {
2742             al = SSL_AD_INTERNAL_ERROR;
2743             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2744             goto psk_err;
2745         }
2746         psk_err = 0;
2747  psk_err:
2748         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2749         if (psk_err != 0)
2750             goto f_err;
2751     } else
2752 #endif
2753 #ifndef OPENSSL_NO_SRP
2754     if (alg_k & SSL_kSRP) {
2755         int param_len;
2756
2757         n2s(p, i);
2758         param_len = i + 2;
2759         if (param_len > n) {
2760             al = SSL_AD_DECODE_ERROR;
2761             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2762                    SSL_R_BAD_SRP_A_LENGTH);
2763             goto f_err;
2764         }
2765         if ((s->srp_ctx.A = BN_bin2bn(p, i, NULL)) == NULL) {
2766             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_BN_LIB);
2767             goto err;
2768         }
2769         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2770             || BN_is_zero(s->srp_ctx.A)) {
2771             al = SSL_AD_ILLEGAL_PARAMETER;
2772             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2773                    SSL_R_BAD_SRP_PARAMETERS);
2774             goto f_err;
2775         }
2776         OPENSSL_free(s->session->srp_username);
2777         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2778         if (s->session->srp_username == NULL) {
2779             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
2780             goto err;
2781         }
2782
2783         if ((s->session->master_key_length =
2784              SRP_generate_server_master_secret(s,
2785                                                s->session->master_key)) < 0) {
2786             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2787             goto err;
2788         }
2789
2790         p += i;
2791     } else
2792 #endif                          /* OPENSSL_NO_SRP */
2793     if (alg_k & SSL_kGOST) {
2794         int ret = 0;
2795         EVP_PKEY_CTX *pkey_ctx;
2796         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2797         unsigned char premaster_secret[32], *start;
2798         size_t outlen = 32, inlen;
2799         unsigned long alg_a;
2800         int Ttag, Tclass;
2801         long Tlen;
2802
2803         /* Get our certificate private key */
2804         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2805         if (alg_a & SSL_aGOST94)
2806             pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2807         else if (alg_a & SSL_aGOST01)
2808             pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2809
2810         pkey_ctx = EVP_PKEY_CTX_new(pk, NULL);
2811         EVP_PKEY_decrypt_init(pkey_ctx);
2812         /*
2813          * If client certificate is present and is of the same type, maybe
2814          * use it for key exchange.  Don't mind errors from
2815          * EVP_PKEY_derive_set_peer, because it is completely valid to use a
2816          * client certificate for authorization only.
2817          */
2818         client_pub_pkey = X509_get_pubkey(s->session->peer);
2819         if (client_pub_pkey) {
2820             if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2821                 ERR_clear_error();
2822         }
2823         /* Decrypt session key */
2824         if (ASN1_get_object
2825             ((const unsigned char **)&p, &Tlen, &Ttag, &Tclass,
2826              n) != V_ASN1_CONSTRUCTED || Ttag != V_ASN1_SEQUENCE
2827             || Tclass != V_ASN1_UNIVERSAL) {
2828             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2829                    SSL_R_DECRYPTION_FAILED);
2830             goto gerr;
2831         }
2832         start = p;
2833         inlen = Tlen;
2834         if (EVP_PKEY_decrypt
2835             (pkey_ctx, premaster_secret, &outlen, start, inlen) <= 0) {
2836             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2837                    SSL_R_DECRYPTION_FAILED);
2838             goto gerr;
2839         }
2840         /* Generate master secret */
2841         s->session->master_key_length =
2842             s->method->ssl3_enc->generate_master_secret(s,
2843                                                         s->
2844                                                         session->master_key,
2845                                                         premaster_secret, 32);
2846         if (s->session->master_key_length < 0) {
2847             al = SSL_AD_INTERNAL_ERROR;
2848             SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2849             goto f_err;
2850         }
2851         /* Check if pubkey from client certificate was used */
2852         if (EVP_PKEY_CTX_ctrl
2853             (pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2854             ret = 2;
2855         else
2856             ret = 1;
2857  gerr:
2858         EVP_PKEY_free(client_pub_pkey);
2859         EVP_PKEY_CTX_free(pkey_ctx);
2860         if (ret)
2861             return ret;
2862         goto err;
2863     } else {
2864         al = SSL_AD_HANDSHAKE_FAILURE;
2865         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, SSL_R_UNKNOWN_CIPHER_TYPE);
2866         goto f_err;
2867     }
2868
2869     return (1);
2870  f_err:
2871     ssl3_send_alert(s, SSL3_AL_FATAL, al);
2872 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_EC) || defined(OPENSSL_NO_SRP)
2873  err:
2874 #endif
2875 #ifndef OPENSSL_NO_EC
2876     EVP_PKEY_free(clnt_pub_pkey);
2877     EC_POINT_free(clnt_ecpoint);
2878     EC_KEY_free(srvr_ecdh);
2879     BN_CTX_free(bn_ctx);
2880 #endif
2881     s->state = SSL_ST_ERR;
2882     return (-1);
2883 }
2884
2885 int ssl3_get_cert_verify(SSL *s)
2886 {
2887     EVP_PKEY *pkey = NULL;
2888     unsigned char *p;
2889     int al, ok, ret = 0;
2890     long n;
2891     int type = 0, i, j;
2892     X509 *peer;
2893     const EVP_MD *md = NULL;
2894     EVP_MD_CTX mctx;
2895     EVP_MD_CTX_init(&mctx);
2896
2897     /*
2898      * We should only process a CertificateVerify message if we have received
2899      * a Certificate from the client. If so then |s->session->peer| will be non
2900      * NULL. In some instances a CertificateVerify message is not required even
2901      * if the peer has sent a Certificate (e.g. such as in the case of static
2902      * DH). In that case the ClientKeyExchange processing will skip the
2903      * CertificateVerify state so we should not arrive here.
2904      */
2905     if (s->session->peer == NULL) {
2906         ret = 1;
2907         goto end;
2908     }
2909
2910     n = s->method->ssl_get_message(s,
2911                                    SSL3_ST_SR_CERT_VRFY_A,
2912                                    SSL3_ST_SR_CERT_VRFY_B,
2913                                    SSL3_MT_CERTIFICATE_VERIFY,
2914                                    SSL3_RT_MAX_PLAIN_LENGTH, &ok);
2915
2916     if (!ok)
2917         return ((int)n);
2918
2919     peer = s->session->peer;
2920     pkey = X509_get_pubkey(peer);
2921     type = X509_certificate_type(peer, pkey);
2922
2923     if (!(type & EVP_PKT_SIGN)) {
2924         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2925                SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2926         al = SSL_AD_ILLEGAL_PARAMETER;
2927         goto f_err;
2928     }
2929
2930     /* we now have a signature that we need to verify */
2931     p = (unsigned char *)s->init_msg;
2932     /* Check for broken implementations of GOST ciphersuites */
2933     /*
2934      * If key is GOST and n is exactly 64, it is bare signature without
2935      * length field
2936      */
2937     if (n == 64 && (pkey->type == NID_id_GostR3410_94 ||
2938                     pkey->type == NID_id_GostR3410_2001)) {
2939         i = 64;
2940     } else {
2941         if (SSL_USE_SIGALGS(s)) {
2942             int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
2943             if (rv == -1) {
2944                 al = SSL_AD_INTERNAL_ERROR;
2945                 goto f_err;
2946             } else if (rv == 0) {
2947                 al = SSL_AD_DECODE_ERROR;
2948                 goto f_err;
2949             }
2950 #ifdef SSL_DEBUG
2951             fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2952 #endif
2953             p += 2;
2954             n -= 2;
2955         }
2956         n2s(p, i);
2957         n -= 2;
2958         if (i > n) {
2959             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_LENGTH_MISMATCH);
2960             al = SSL_AD_DECODE_ERROR;
2961             goto f_err;
2962         }
2963     }
2964     j = EVP_PKEY_size(pkey);
2965     if ((i > j) || (n > j) || (n <= 0)) {
2966         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_WRONG_SIGNATURE_SIZE);
2967         al = SSL_AD_DECODE_ERROR;
2968         goto f_err;
2969     }
2970
2971     if (SSL_USE_SIGALGS(s)) {
2972         long hdatalen = 0;
2973         void *hdata;
2974         hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
2975         if (hdatalen <= 0) {
2976             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
2977             al = SSL_AD_INTERNAL_ERROR;
2978             goto f_err;
2979         }
2980 #ifdef SSL_DEBUG
2981         fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
2982                 EVP_MD_name(md));
2983 #endif
2984         if (!EVP_VerifyInit_ex(&mctx, md, NULL)
2985             || !EVP_VerifyUpdate(&mctx, hdata, hdatalen)) {
2986             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
2987             al = SSL_AD_INTERNAL_ERROR;
2988             goto f_err;
2989         }
2990
2991         if (EVP_VerifyFinal(&mctx, p, i, pkey) <= 0) {
2992             al = SSL_AD_DECRYPT_ERROR;
2993             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_SIGNATURE);
2994             goto f_err;
2995         }
2996     } else
2997 #ifndef OPENSSL_NO_RSA
2998     if (pkey->type == EVP_PKEY_RSA) {
2999         i = RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3000                        MD5_DIGEST_LENGTH + SHA_DIGEST_LENGTH, p, i,
3001                        pkey->pkey.rsa);
3002         if (i < 0) {
3003             al = SSL_AD_DECRYPT_ERROR;
3004             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_DECRYPT);
3005             goto f_err;
3006         }
3007         if (i == 0) {
3008             al = SSL_AD_DECRYPT_ERROR;
3009             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_RSA_SIGNATURE);
3010             goto f_err;
3011         }
3012     } else
3013 #endif
3014 #ifndef OPENSSL_NO_DSA
3015     if (pkey->type == EVP_PKEY_DSA) {
3016         j = DSA_verify(pkey->save_type,
3017                        &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3018                        SHA_DIGEST_LENGTH, p, i, pkey->pkey.dsa);
3019         if (j <= 0) {
3020             /* bad signature */
3021             al = SSL_AD_DECRYPT_ERROR;
3022             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_DSA_SIGNATURE);
3023             goto f_err;
3024         }
3025     } else
3026 #endif
3027 #ifndef OPENSSL_NO_EC
3028     if (pkey->type == EVP_PKEY_EC) {
3029         j = ECDSA_verify(pkey->save_type,
3030                          &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3031                          SHA_DIGEST_LENGTH, p, i, pkey->pkey.ec);
3032         if (j <= 0) {
3033             /* bad signature */
3034             al = SSL_AD_DECRYPT_ERROR;
3035             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3036             goto f_err;
3037         }
3038     } else
3039 #endif
3040     if (pkey->type == NID_id_GostR3410_94
3041             || pkey->type == NID_id_GostR3410_2001) {
3042         unsigned char signature[64];
3043         int idx;
3044         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey, NULL);
3045         EVP_PKEY_verify_init(pctx);
3046         if (i != 64) {
3047             fprintf(stderr, "GOST signature length is %d", i);
3048         }
3049         for (idx = 0; idx < 64; idx++) {
3050             signature[63 - idx] = p[idx];
3051         }
3052         j = EVP_PKEY_verify(pctx, signature, 64, s->s3->tmp.cert_verify_md,
3053                             32);
3054         EVP_PKEY_CTX_free(pctx);
3055         if (j <= 0) {
3056             al = SSL_AD_DECRYPT_ERROR;
3057             SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, SSL_R_BAD_ECDSA_SIGNATURE);
3058             goto f_err;
3059         }
3060     } else {
3061         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3062         al = SSL_AD_UNSUPPORTED_CERTIFICATE;
3063         goto f_err;
3064     }
3065
3066     ret = 1;
3067     if (0) {
3068  f_err:
3069         ssl3_send_alert(s, SSL3_AL_FATAL, al);
3070         s->state = SSL_ST_ERR;
3071     }
3072  end:
3073     BIO_free(s->s3->handshake_buffer);
3074     s->s3->handshake_buffer = NULL;
3075     s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3076     EVP_MD_CTX_cleanup(&mctx);
3077     EVP_PKEY_free(pkey);
3078     return (ret);
3079 }
3080
3081 int ssl3_get_client_certificate(SSL *s)
3082 {
3083     int i, ok, al, ret = -1;
3084     X509 *x = NULL;
3085     unsigned long l, nc, llen, n;
3086     const unsigned char *p, *q;
3087     unsigned char *d;
3088     STACK_OF(X509) *sk = NULL;
3089
3090     n = s->method->ssl_get_message(s,
3091                                    SSL3_ST_SR_CERT_A,
3092                                    SSL3_ST_SR_CERT_B,
3093                                    -1, s->max_cert_list, &ok);
3094
3095     if (!ok)
3096         return ((int)n);
3097
3098     if (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE) {
3099         if ((s->verify_mode & SSL_VERIFY_PEER) &&
3100             (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3101             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3102                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3103             al = SSL_AD_HANDSHAKE_FAILURE;
3104             goto f_err;
3105         }
3106         /*
3107          * If tls asked for a client cert, the client must return a 0 list
3108          */
3109         if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request) {
3110             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3111                    SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3112             al = SSL_AD_UNEXPECTED_MESSAGE;
3113             goto f_err;
3114         }
3115         s->s3->tmp.reuse_message = 1;
3116         return (1);
3117     }
3118
3119     if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE) {
3120         al = SSL_AD_UNEXPECTED_MESSAGE;
3121         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_WRONG_MESSAGE_TYPE);
3122         goto f_err;
3123     }
3124     p = d = (unsigned char *)s->init_msg;
3125
3126     if ((sk = sk_X509_new_null()) == NULL) {
3127         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3128         goto done;
3129     }
3130
3131     n2l3(p, llen);
3132     if (llen + 3 != n) {
3133         al = SSL_AD_DECODE_ERROR;
3134         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, SSL_R_LENGTH_MISMATCH);
3135         goto f_err;
3136     }
3137     for (nc = 0; nc < llen;) {
3138         n2l3(p, l);
3139         if ((l + nc + 3) > llen) {
3140             al = SSL_AD_DECODE_ERROR;
3141             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3142                    SSL_R_CERT_LENGTH_MISMATCH);
3143             goto f_err;
3144         }
3145
3146         q = p;
3147         x = d2i_X509(NULL, &p, l);
3148         if (x == NULL) {
3149             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_ASN1_LIB);
3150             goto done;
3151         }
3152         if (p != (q + l)) {
3153             al = SSL_AD_DECODE_ERROR;
3154             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3155                    SSL_R_CERT_LENGTH_MISMATCH);
3156             goto f_err;
3157         }
3158         if (!sk_X509_push(sk, x)) {
3159             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3160             goto done;
3161         }
3162         x = NULL;
3163         nc += l + 3;
3164     }
3165
3166     if (sk_X509_num(sk) <= 0) {
3167         /* TLS does not mind 0 certs returned */
3168         if (s->version == SSL3_VERSION) {
3169             al = SSL_AD_HANDSHAKE_FAILURE;
3170             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3171                    SSL_R_NO_CERTIFICATES_RETURNED);
3172             goto f_err;
3173         }
3174         /* Fail for TLS only if we required a certificate */
3175         else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3176                  (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) {
3177             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3178                    SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3179             al = SSL_AD_HANDSHAKE_FAILURE;
3180             goto f_err;
3181         }
3182         /* No client certificate so digest cached records */
3183         if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s)) {
3184             al = SSL_AD_INTERNAL_ERROR;
3185             goto f_err;
3186         }
3187     } else {
3188         EVP_PKEY *pkey;
3189         i = ssl_verify_cert_chain(s, sk);
3190         if (i <= 0) {
3191             al = ssl_verify_alarm_type(s->verify_result);
3192             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3193                    SSL_R_CERTIFICATE_VERIFY_FAILED);
3194             goto f_err;
3195         }
3196         if (i > 1) {
3197             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, i);
3198             al = SSL_AD_HANDSHAKE_FAILURE;
3199             goto f_err;
3200         }
3201         pkey = X509_get_pubkey(sk_X509_value(sk, 0));
3202         if (pkey == NULL) {
3203             al = SSL3_AD_HANDSHAKE_FAILURE;
3204             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,
3205                    SSL_R_UNKNOWN_CERTIFICATE_TYPE);
3206             goto f_err;
3207         }
3208         EVP_PKEY_free(pkey);
3209     }
3210
3211     X509_free(s->session->peer);
3212     s->session->peer = sk_X509_shift(sk);
3213     s->session->verify_result = s->verify_result;
3214
3215     /*
3216      * With the current implementation, sess_cert will always be NULL when we
3217      * arrive here.
3218      */
3219     if (s->session->sess_cert == NULL) {
3220         s->session->sess_cert = ssl_sess_cert_new();
3221         if (s->session->sess_cert == NULL) {
3222             SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3223             goto done;
3224         }
3225     }
3226     sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3227     s->session->sess_cert->cert_chain = sk;
3228     /*
3229      * Inconsistency alert: cert_chain does *not* include the peer's own
3230      * certificate, while we do include it in s3_clnt.c
3231      */
3232     sk = NULL;
3233     ret = 1;
3234     goto done;
3235
3236  f_err:
3237     ssl3_send_alert(s, SSL3_AL_FATAL, al);
3238  done:
3239     s->state = SSL_ST_ERR;
3240     X509_free(x);
3241     sk_X509_pop_free(sk, X509_free);
3242     return (ret);
3243 }
3244
3245 int ssl3_send_server_certificate(SSL *s)
3246 {
3247     CERT_PKEY *cpk;
3248
3249     if (s->state == SSL3_ST_SW_CERT_A) {
3250         cpk = ssl_get_server_send_pkey(s);
3251         if (cpk == NULL) {
3252             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3253             s->state = SSL_ST_ERR;
3254             return (0);
3255         }
3256
3257         if (!ssl3_output_cert_chain(s, cpk)) {
3258             SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE, ERR_R_INTERNAL_ERROR);
3259             s->state = SSL_ST_ERR;
3260             return (0);
3261         }
3262         s->state = SSL3_ST_SW_CERT_B;
3263     }
3264
3265     /* SSL3_ST_SW_CERT_B */
3266     return ssl_do_write(s);
3267 }
3268
3269 #ifndef OPENSSL_NO_TLSEXT
3270 /* send a new session ticket (not necessarily for a new session) */
3271 int ssl3_send_newsession_ticket(SSL *s)
3272 {
3273     unsigned char *senc = NULL;
3274     EVP_CIPHER_CTX ctx;
3275     HMAC_CTX hctx;
3276
3277     if (s->state == SSL3_ST_SW_SESSION_TICKET_A) {
3278         unsigned char *p, *macstart;
3279         const unsigned char *const_p;
3280         int len, slen_full, slen;
3281         SSL_SESSION *sess;
3282         unsigned int hlen;
3283         SSL_CTX *tctx = s->initial_ctx;
3284         unsigned char iv[EVP_MAX_IV_LENGTH];
3285         unsigned char key_name[16];
3286
3287         /* get session encoding length */
3288         slen_full = i2d_SSL_SESSION(s->session, NULL);
3289         /*
3290          * Some length values are 16 bits, so forget it if session is too
3291          * long
3292          */
3293         if (slen_full == 0 || slen_full > 0xFF00) {
3294             s->state = SSL_ST_ERR;
3295             return -1;
3296         }
3297         senc = OPENSSL_malloc(slen_full);
3298         if (!senc) {
3299             s->state = SSL_ST_ERR;
3300             return -1;
3301         }
3302
3303         EVP_CIPHER_CTX_init(&ctx);
3304         HMAC_CTX_init(&hctx);
3305
3306         p = senc;
3307         if (!i2d_SSL_SESSION(s->session, &p))
3308             goto err;
3309
3310         /*
3311          * create a fresh copy (not shared with other threads) to clean up
3312          */
3313         const_p = senc;
3314         sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3315         if (sess == NULL)
3316             goto err;
3317         sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3318
3319         slen = i2d_SSL_SESSION(sess, NULL);
3320         if (slen == 0 || slen > slen_full) { /* shouldn't ever happen */
3321             SSL_SESSION_free(sess);
3322             goto err;
3323         }
3324         p = senc;
3325         if (!i2d_SSL_SESSION(sess, &p)) {
3326             SSL_SESSION_free(sess);
3327             goto err;
3328         }
3329         SSL_SESSION_free(sess);
3330
3331         /*-
3332          * Grow buffer if need be: the length calculation is as
3333          * follows handshake_header_length +
3334          * 4 (ticket lifetime hint) + 2 (ticket length) +
3335          * 16 (key name) + max_iv_len (iv length) +
3336          * session_length + max_enc_block_size (max encrypted session
3337          * length) + max_md_size (HMAC).
3338          */
3339         if (!BUF_MEM_grow(s->init_buf,
3340                           SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3341                           EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3342             goto err;
3343
3344         p = ssl_handshake_start(s);
3345         /*
3346          * Initialize HMAC and cipher contexts. If callback present it does
3347          * all the work otherwise use generated values from parent ctx.
3348          */
3349         if (tctx->tlsext_ticket_key_cb) {
3350             if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3351                                            &hctx, 1) < 0)
3352                 goto err;
3353         } else {
3354             if (RAND_bytes(iv, 16) <= 0)
3355                 goto err;
3356             if (!EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3357                                     tctx->tlsext_tick_aes_key, iv))
3358                 goto err;
3359             if (!HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3360                               EVP_sha256(), NULL))
3361                 goto err;
3362             memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3363         }
3364
3365         /*
3366          * Ticket lifetime hint (advisory only): We leave this unspecified
3367          * for resumed session (for simplicity), and guess that tickets for
3368          * new sessions will live as long as their sessions.
3369          */
3370         l2n(s->hit ? 0 : s->session->timeout, p);
3371
3372         /* Skip ticket length for now */
3373         p += 2;
3374         /* Output key name */
3375         macstart = p;
3376         memcpy(p, key_name, 16);
3377         p += 16;
3378         /* output IV */
3379         memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3380         p += EVP_CIPHER_CTX_iv_length(&ctx);
3381         /* Encrypt session data */
3382         if (!EVP_EncryptUpdate(&ctx, p, &len, senc, slen))
3383             goto err;
3384         p += len;
3385         if (!EVP_EncryptFinal(&ctx, p, &len))
3386             goto err;
3387         p += len;
3388
3389         if (!HMAC_Update(&hctx, macstart, p - macstart))
3390             goto err;
3391         if (!HMAC_Final(&hctx, p, &hlen))
3392             goto err;
3393
3394         EVP_CIPHER_CTX_cleanup(&ctx);
3395         HMAC_CTX_cleanup(&hctx);
3396
3397         p += hlen;
3398         /* Now write out lengths: p points to end of data written */
3399         /* Total length */
3400         len = p - ssl_handshake_start(s);
3401         /* Skip ticket lifetime hint */
3402         p = ssl_handshake_start(s) + 4;
3403         s2n(len - 6, p);
3404         if (!ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len))
3405             goto err;
3406         s->state = SSL3_ST_SW_SESSION_TICKET_B;
3407         OPENSSL_free(senc);
3408     }
3409
3410     /* SSL3_ST_SW_SESSION_TICKET_B */
3411     return ssl_do_write(s);
3412  err:
3413     OPENSSL_free(senc);
3414     EVP_CIPHER_CTX_cleanup(&ctx);
3415     HMAC_CTX_cleanup(&hctx);
3416     s->state = SSL_ST_ERR;
3417     return -1;
3418 }
3419
3420 int ssl3_send_cert_status(SSL *s)
3421 {
3422     if (s->state == SSL3_ST_SW_CERT_STATUS_A) {
3423         unsigned char *p;
3424         /*-
3425          * Grow buffer if need be: the length calculation is as
3426          * follows 1 (message type) + 3 (message length) +
3427          * 1 (ocsp response type) + 3 (ocsp response length)
3428          * + (ocsp response)
3429          */
3430         if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen)) {
3431             s->state = SSL_ST_ERR;
3432             return -1;
3433         }
3434
3435         p = (unsigned char *)s->init_buf->data;
3436
3437         /* do the header */
3438         *(p++) = SSL3_MT_CERTIFICATE_STATUS;
3439         /* message length */
3440         l2n3(s->tlsext_ocsp_resplen + 4, p);
3441         /* status type */
3442         *(p++) = s->tlsext_status_type;
3443         /* length of OCSP response */
3444         l2n3(s->tlsext_ocsp_resplen, p);
3445         /* actual response */
3446         memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3447         /* number of bytes to write */
3448         s->init_num = 8 + s->tlsext_ocsp_resplen;
3449         s->state = SSL3_ST_SW_CERT_STATUS_B;
3450         s->init_off = 0;
3451     }
3452
3453     /* SSL3_ST_SW_CERT_STATUS_B */
3454     return (ssl3_do_write(s, SSL3_RT_HANDSHAKE));
3455 }
3456
3457 # ifndef OPENSSL_NO_NEXTPROTONEG
3458 /*
3459  * ssl3_get_next_proto reads a Next Protocol Negotiation handshake message.
3460  * It sets the next_proto member in s if found
3461  */
3462 int ssl3_get_next_proto(SSL *s)
3463 {
3464     int ok;
3465     int proto_len, padding_len;
3466     long n;
3467     const unsigned char *p;
3468
3469     /*
3470      * Clients cannot send a NextProtocol message if we didn't see the
3471      * extension in their ClientHello
3472      */
3473     if (!s->s3->next_proto_neg_seen) {
3474         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,
3475                SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3476         s->state = SSL_ST_ERR;
3477         return -1;
3478     }
3479
3480     /* See the payload format below */
3481     n = s->method->ssl_get_message(s,
3482                                    SSL3_ST_SR_NEXT_PROTO_A,
3483                                    SSL3_ST_SR_NEXT_PROTO_B,
3484                                    SSL3_MT_NEXT_PROTO, 514, &ok);
3485
3486     if (!ok)
3487         return ((int)n);
3488
3489     /*
3490      * s->state doesn't reflect whether ChangeCipherSpec has been received in
3491      * this handshake, but s->s3->change_cipher_spec does (will be reset by
3492      * ssl3_get_finished).
3493      */
3494     if (!s->s3->change_cipher_spec) {
3495         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3496         s->state = SSL_ST_ERR;
3497         return -1;
3498     }
3499
3500     if (n < 2) {
3501         s->state = SSL_ST_ERR;
3502         return 0;               /* The body must be > 1 bytes long */
3503     }
3504
3505     p = (unsigned char *)s->init_msg;
3506
3507     /*-
3508      * The payload looks like:
3509      *   uint8 proto_len;
3510      *   uint8 proto[proto_len];
3511      *   uint8 padding_len;
3512      *   uint8 padding[padding_len];
3513      */
3514     proto_len = p[0];
3515     if (proto_len + 2 > s->init_num) {
3516         s->state = SSL_ST_ERR;
3517         return 0;
3518     }
3519     padding_len = p[proto_len + 1];
3520     if (proto_len + padding_len + 2 != s->init_num) {
3521         s->state = SSL_ST_ERR;
3522         return 0;
3523     }
3524
3525     s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3526     if (!s->next_proto_negotiated) {
3527         SSLerr(SSL_F_SSL3_GET_NEXT_PROTO, ERR_R_MALLOC_FAILURE);
3528         s->state = SSL_ST_ERR;
3529         return 0;
3530     }
3531     memcpy(s->next_proto_negotiated, p + 1, proto_len);
3532     s->next_proto_negotiated_len = proto_len;
3533
3534     return 1;
3535 }
3536 # endif
3537
3538 #endif
3539
3540 #define SSLV2_CIPHER_LEN    3
3541
3542 STACK_OF(SSL_CIPHER) *ssl_bytes_to_cipher_list(SSL *s, unsigned char *p,
3543                                                int num,
3544                                                STACK_OF(SSL_CIPHER) **skp,
3545                                                int sslv2format)
3546 {
3547     const SSL_CIPHER *c;
3548     STACK_OF(SSL_CIPHER) *sk;
3549     int i, n;
3550
3551     if (s->s3)
3552         s->s3->send_connection_binding = 0;
3553
3554     if(sslv2format) {
3555         n = SSLV2_CIPHER_LEN;
3556     } else {
3557         n = ssl_put_cipher_by_char(s, NULL, NULL);
3558     }
3559     if (n == 0 || (num % n) != 0) {
3560         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3561                SSL_R_ERROR_IN_RECEIVED_CIPHER_LIST);
3562         return (NULL);
3563     }
3564     if ((skp == NULL) || (*skp == NULL)) {
3565         sk = sk_SSL_CIPHER_new_null(); /* change perhaps later */
3566         if(sk == NULL) {
3567             SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3568             return NULL;
3569         }
3570     } else {
3571         sk = *skp;
3572         sk_SSL_CIPHER_zero(sk);
3573     }
3574
3575     OPENSSL_free(s->s3->tmp.ciphers_raw);
3576     s->s3->tmp.ciphers_raw = BUF_memdup(p, num);
3577     if (s->s3->tmp.ciphers_raw == NULL) {
3578         SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3579         goto err;
3580     }
3581     s->s3->tmp.ciphers_rawlen = (size_t)num;
3582
3583     for (i = 0; i < num; i += n) {
3584         /* Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */
3585         if (s->s3 && (n != 3 || !p[0]) &&
3586             (p[n - 2] == ((SSL3_CK_SCSV >> 8) & 0xff)) &&
3587             (p[n - 1] == (SSL3_CK_SCSV & 0xff))) {
3588             /* SCSV fatal if renegotiating */
3589             if (s->renegotiate) {
3590                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3591                        SSL_R_SCSV_RECEIVED_WHEN_RENEGOTIATING);
3592                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3593                 goto err;
3594             }
3595             s->s3->send_connection_binding = 1;
3596             p += n;
3597 #ifdef OPENSSL_RI_DEBUG
3598             fprintf(stderr, "SCSV received by server\n");
3599 #endif
3600             continue;
3601         }
3602
3603         /* Check for TLS_FALLBACK_SCSV */
3604         if ((n != 3 || !p[0]) &&
3605             (p[n - 2] == ((SSL3_CK_FALLBACK_SCSV >> 8) & 0xff)) &&
3606             (p[n - 1] == (SSL3_CK_FALLBACK_SCSV & 0xff))) {
3607             /*
3608              * The SCSV indicates that the client previously tried a higher
3609              * version. Fail if the current version is an unexpected
3610              * downgrade.
3611              */
3612             if (!SSL_ctrl(s, SSL_CTRL_CHECK_PROTO_VERSION, 0, NULL)) {
3613                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST,
3614                        SSL_R_INAPPROPRIATE_FALLBACK);
3615                 if (s->s3)
3616                     ssl3_send_alert(s, SSL3_AL_FATAL,
3617                                     SSL_AD_INAPPROPRIATE_FALLBACK);
3618                 goto err;
3619             }
3620             p += n;
3621             continue;
3622         }
3623
3624         if(sslv2format) {
3625             /*
3626              * We only support SSLv2 format ciphers in SSLv3+ using a
3627              * SSLv2 backward compatible ClientHello. In this case the first
3628              * byte is always 0 for SSLv3 compatible ciphers. Anything else
3629              * is an SSLv2 cipher and we ignore it
3630              */
3631             if(p[0] == 0)
3632                 c = ssl_get_cipher_by_char(s, &p[1]);
3633             else
3634                 c = NULL;
3635         } else {
3636             c = ssl_get_cipher_by_char(s, p);
3637         }
3638         p += n;
3639         if (c != NULL) {
3640             if (!sk_SSL_CIPHER_push(sk, c)) {
3641                 SSLerr(SSL_F_SSL_BYTES_TO_CIPHER_LIST, ERR_R_MALLOC_FAILURE);
3642                 goto err;
3643             }
3644         }
3645     }
3646
3647     if (skp != NULL)
3648         *skp = sk;
3649     return (sk);
3650  err:
3651     if ((skp == NULL) || (*skp == NULL))
3652         sk_SSL_CIPHER_free(sk);
3653     return (NULL);
3654 }