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