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