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