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