Set s->hit when resuming from external pre-shared secret.
[openssl.git] / ssl / s3_clnt.c
1 /* ssl/s3_clnt.c */
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 #include <stdio.h>
152 #include "ssl_locl.h"
153 #include "kssl_lcl.h"
154 #include <openssl/buffer.h>
155 #include <openssl/rand.h>
156 #include <openssl/objects.h>
157 #include <openssl/evp.h>
158 #include <openssl/md5.h>
159 #ifdef OPENSSL_FIPS
160 #include <openssl/fips.h>
161 #endif
162 #ifndef OPENSSL_NO_DH
163 #include <openssl/dh.h>
164 #endif
165 #include <openssl/bn.h>
166 #ifndef OPENSSL_NO_ENGINE
167 #include <openssl/engine.h>
168 #endif
169
170 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
171
172 #ifndef OPENSSL_NO_SSL3_METHOD
173 static const SSL_METHOD *ssl3_get_client_method(int ver)
174         {
175         if (ver == SSL3_VERSION)
176                 return(SSLv3_client_method());
177         else
178                 return(NULL);
179         }
180
181 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
182                         ssl_undefined_function,
183                         ssl3_connect,
184                         ssl3_get_client_method)
185 #endif
186
187 int ssl3_connect(SSL *s)
188         {
189         BUF_MEM *buf=NULL;
190         unsigned long Time=(unsigned long)time(NULL);
191         void (*cb)(const SSL *ssl,int type,int val)=NULL;
192         int ret= -1;
193         int new_state,state,skip=0;
194
195         RAND_add(&Time,sizeof(Time),0);
196         ERR_clear_error();
197         clear_sys_error();
198
199         if (s->info_callback != NULL)
200                 cb=s->info_callback;
201         else if (s->ctx->info_callback != NULL)
202                 cb=s->ctx->info_callback;
203         
204         s->in_handshake++;
205         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
206
207 #ifndef OPENSSL_NO_HEARTBEATS
208         /* If we're awaiting a HeartbeatResponse, pretend we
209          * already got and don't await it anymore, because
210          * Heartbeats don't make sense during handshakes anyway.
211          */
212         if (s->tlsext_hb_pending)
213                 {
214                 s->tlsext_hb_pending = 0;
215                 s->tlsext_hb_seq++;
216                 }
217 #endif
218
219         for (;;)
220                 {
221                 state=s->state;
222
223                 switch(s->state)
224                         {
225                 case SSL_ST_RENEGOTIATE:
226                         s->renegotiate=1;
227                         s->state=SSL_ST_CONNECT;
228                         s->ctx->stats.sess_connect_renegotiate++;
229                         /* break */
230                 case SSL_ST_BEFORE:
231                 case SSL_ST_CONNECT:
232                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
233                 case SSL_ST_OK|SSL_ST_CONNECT:
234
235                         s->server=0;
236                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
237
238                         if ((s->version & 0xff00 ) != 0x0300)
239                                 {
240                                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
241                                 ret = -1;
242                                 goto end;
243                                 }
244                                 
245                         /* s->version=SSL3_VERSION; */
246                         s->type=SSL_ST_CONNECT;
247
248                         if (s->init_buf == NULL)
249                                 {
250                                 if ((buf=BUF_MEM_new()) == NULL)
251                                         {
252                                         ret= -1;
253                                         goto end;
254                                         }
255                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
256                                         {
257                                         ret= -1;
258                                         goto end;
259                                         }
260                                 s->init_buf=buf;
261                                 buf=NULL;
262                                 }
263
264                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
265
266                         /* setup buffing BIO */
267                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
268
269                         /* don't push the buffering BIO quite yet */
270
271                         ssl3_init_finished_mac(s);
272
273                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
274                         s->ctx->stats.sess_connect++;
275                         s->init_num=0;
276                         break;
277
278                 case SSL3_ST_CW_CLNT_HELLO_A:
279                 case SSL3_ST_CW_CLNT_HELLO_B:
280
281                         s->shutdown=0;
282                         ret=ssl3_client_hello(s);
283                         if (ret <= 0) goto end;
284                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
285                         s->init_num=0;
286
287                         /* turn on buffering for the next lot of output */
288                         if (s->bbio != s->wbio)
289                                 s->wbio=BIO_push(s->bbio,s->wbio);
290
291                         break;
292
293                 case SSL3_ST_CR_SRVR_HELLO_A:
294                 case SSL3_ST_CR_SRVR_HELLO_B:
295                         ret=ssl3_get_server_hello(s);
296                         if (ret <= 0) goto end;
297
298                         if (s->hit)
299                                 {
300                                 s->state=SSL3_ST_CR_FINISHED_A;
301 #ifndef OPENSSL_NO_TLSEXT
302                                 if (s->tlsext_ticket_expected)
303                                         {
304                                         /* receive renewed session ticket */
305                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
306                                         }
307 #endif
308                                 }
309                         else
310                                 s->state=SSL3_ST_CR_CERT_A;
311                         s->init_num=0;
312                         break;
313
314                 case SSL3_ST_CR_CERT_A:
315                 case SSL3_ST_CR_CERT_B:
316 #ifndef OPENSSL_NO_TLSEXT
317                         ret=ssl3_check_finished(s);
318                         if (ret <= 0) goto end;
319                         if (ret == 2)
320                                 {
321                                 s->hit = 1;
322                                 if (s->tlsext_ticket_expected)
323                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
324                                 else
325                                         s->state=SSL3_ST_CR_FINISHED_A;
326                                 s->init_num=0;
327                                 break;
328                                 }
329 #endif
330                         /* Check if it is anon DH/ECDH, SRP auth */
331                         /* or PSK */
332                         if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP)) &&
333                             !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
334                                 {
335                                 ret=ssl3_get_server_certificate(s);
336                                 if (ret <= 0) goto end;
337 #ifndef OPENSSL_NO_TLSEXT
338                                 if (s->tlsext_status_expected)
339                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
340                                 else
341                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
342                                 }
343                         else
344                                 {
345                                 skip = 1;
346                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
347                                 }
348 #else
349                                 }
350                         else
351                                 skip=1;
352
353                         s->state=SSL3_ST_CR_KEY_EXCH_A;
354 #endif
355                         s->init_num=0;
356                         break;
357
358                 case SSL3_ST_CR_KEY_EXCH_A:
359                 case SSL3_ST_CR_KEY_EXCH_B:
360                         ret=ssl3_get_key_exchange(s);
361                         if (ret <= 0) goto end;
362                         s->state=SSL3_ST_CR_CERT_REQ_A;
363                         s->init_num=0;
364
365                         /* at this point we check that we have the
366                          * required stuff from the server */
367                         if (!ssl3_check_cert_and_algorithm(s))
368                                 {
369                                 ret= -1;
370                                 goto end;
371                                 }
372                         break;
373
374                 case SSL3_ST_CR_CERT_REQ_A:
375                 case SSL3_ST_CR_CERT_REQ_B:
376                         ret=ssl3_get_certificate_request(s);
377                         if (ret <= 0) goto end;
378                         s->state=SSL3_ST_CR_SRVR_DONE_A;
379                         s->init_num=0;
380                         break;
381
382                 case SSL3_ST_CR_SRVR_DONE_A:
383                 case SSL3_ST_CR_SRVR_DONE_B:
384                         ret=ssl3_get_server_done(s);
385                         if (ret <= 0) goto end;
386 #ifndef OPENSSL_NO_SRP
387                         if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP)
388                                 {
389                                 if ((ret = SRP_Calc_A_param(s))<=0)
390                                         {
391                                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_SRP_A_CALC);
392                                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_INTERNAL_ERROR);
393                                         goto end;
394                                         }
395                                 }
396 #endif
397                         if (s->s3->tmp.cert_req)
398                                 s->state=SSL3_ST_CW_CERT_A;
399                         else
400                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
401                         s->init_num=0;
402
403                         break;
404
405                 case SSL3_ST_CW_CERT_A:
406                 case SSL3_ST_CW_CERT_B:
407                 case SSL3_ST_CW_CERT_C:
408                 case SSL3_ST_CW_CERT_D:
409                         ret=ssl3_send_client_certificate(s);
410                         if (ret <= 0) goto end;
411                         s->state=SSL3_ST_CW_KEY_EXCH_A;
412                         s->init_num=0;
413                         break;
414
415                 case SSL3_ST_CW_KEY_EXCH_A:
416                 case SSL3_ST_CW_KEY_EXCH_B:
417                         ret=ssl3_send_client_key_exchange(s);
418                         if (ret <= 0) goto end;
419                         /* EAY EAY EAY need to check for DH fix cert
420                          * sent back */
421                         /* For TLS, cert_req is set to 2, so a cert chain
422                          * of nothing is sent, but no verify packet is sent */
423                         /* XXX: For now, we do not support client 
424                          * authentication in ECDH cipher suites with
425                          * ECDH (rather than ECDSA) certificates.
426                          * We need to skip the certificate verify 
427                          * message when client's ECDH public key is sent 
428                          * inside the client certificate.
429                          */
430                         if (s->s3->tmp.cert_req == 1)
431                                 {
432                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
433                                 }
434                         else
435                                 {
436                                 s->state=SSL3_ST_CW_CHANGE_A;
437                                 s->s3->change_cipher_spec=0;
438                                 }
439                         if (s->s3->flags & TLS1_FLAGS_SKIP_CERT_VERIFY)
440                                 {
441                                 s->state=SSL3_ST_CW_CHANGE_A;
442                                 s->s3->change_cipher_spec=0;
443                                 }
444
445                         s->init_num=0;
446                         break;
447
448                 case SSL3_ST_CW_CERT_VRFY_A:
449                 case SSL3_ST_CW_CERT_VRFY_B:
450                         ret=ssl3_send_client_verify(s);
451                         if (ret <= 0) goto end;
452                         s->state=SSL3_ST_CW_CHANGE_A;
453                         s->init_num=0;
454                         s->s3->change_cipher_spec=0;
455                         break;
456
457                 case SSL3_ST_CW_CHANGE_A:
458                 case SSL3_ST_CW_CHANGE_B:
459                         ret=ssl3_send_change_cipher_spec(s,
460                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
461                         if (ret <= 0) goto end;
462
463 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
464                         s->state=SSL3_ST_CW_FINISHED_A;
465 #else
466                         if (s->s3->next_proto_neg_seen)
467                                 s->state=SSL3_ST_CW_NEXT_PROTO_A;
468                         else
469                                 s->state=SSL3_ST_CW_FINISHED_A;
470 #endif
471                         s->init_num=0;
472
473                         s->session->cipher=s->s3->tmp.new_cipher;
474 #ifdef OPENSSL_NO_COMP
475                         s->session->compress_meth=0;
476 #else
477                         if (s->s3->tmp.new_compression == NULL)
478                                 s->session->compress_meth=0;
479                         else
480                                 s->session->compress_meth=
481                                         s->s3->tmp.new_compression->id;
482 #endif
483                         if (!s->method->ssl3_enc->setup_key_block(s))
484                                 {
485                                 ret= -1;
486                                 goto end;
487                                 }
488
489                         if (!s->method->ssl3_enc->change_cipher_state(s,
490                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
491                                 {
492                                 ret= -1;
493                                 goto end;
494                                 }
495
496                         break;
497
498 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
499                 case SSL3_ST_CW_NEXT_PROTO_A:
500                 case SSL3_ST_CW_NEXT_PROTO_B:
501                         ret=ssl3_send_next_proto(s);
502                         if (ret <= 0) goto end;
503                         s->state=SSL3_ST_CW_FINISHED_A;
504                         break;
505 #endif
506
507                 case SSL3_ST_CW_FINISHED_A:
508                 case SSL3_ST_CW_FINISHED_B:
509                         ret=ssl3_send_finished(s,
510                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
511                                 s->method->ssl3_enc->client_finished_label,
512                                 s->method->ssl3_enc->client_finished_label_len);
513                         if (ret <= 0) goto end;
514                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
515                         s->state=SSL3_ST_CW_FLUSH;
516
517                         /* clear flags */
518                         s->s3->flags&= ~SSL3_FLAGS_POP_BUFFER;
519                         if (s->hit)
520                                 {
521                                 s->s3->tmp.next_state=SSL_ST_OK;
522                                 if (s->s3->flags & SSL3_FLAGS_DELAY_CLIENT_FINISHED)
523                                         {
524                                         s->state=SSL_ST_OK;
525                                         s->s3->flags|=SSL3_FLAGS_POP_BUFFER;
526                                         s->s3->delay_buf_pop_ret=0;
527                                         }
528                                 }
529                         else
530                                 {
531 #ifndef OPENSSL_NO_TLSEXT
532                                 /* Allow NewSessionTicket if ticket expected */
533                                 if (s->tlsext_ticket_expected)
534                                         s->s3->tmp.next_state=SSL3_ST_CR_SESSION_TICKET_A;
535                                 else
536 #endif
537                                 
538                                 s->s3->tmp.next_state=SSL3_ST_CR_FINISHED_A;
539                                 }
540                         s->init_num=0;
541                         break;
542
543 #ifndef OPENSSL_NO_TLSEXT
544                 case SSL3_ST_CR_SESSION_TICKET_A:
545                 case SSL3_ST_CR_SESSION_TICKET_B:
546                         ret=ssl3_get_new_session_ticket(s);
547                         if (ret <= 0) goto end;
548                         s->state=SSL3_ST_CR_FINISHED_A;
549                         s->init_num=0;
550                 break;
551
552                 case SSL3_ST_CR_CERT_STATUS_A:
553                 case SSL3_ST_CR_CERT_STATUS_B:
554                         ret=ssl3_get_cert_status(s);
555                         if (ret <= 0) goto end;
556                         s->state=SSL3_ST_CR_KEY_EXCH_A;
557                         s->init_num=0;
558                 break;
559 #endif
560
561                 case SSL3_ST_CR_FINISHED_A:
562                 case SSL3_ST_CR_FINISHED_B:
563
564                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
565                         ret=ssl3_get_finished(s,SSL3_ST_CR_FINISHED_A,
566                                 SSL3_ST_CR_FINISHED_B);
567                         if (ret <= 0) goto end;
568
569                         if (s->hit)
570                                 s->state=SSL3_ST_CW_CHANGE_A;
571                         else
572                                 s->state=SSL_ST_OK;
573                         s->init_num=0;
574                         break;
575
576                 case SSL3_ST_CW_FLUSH:
577                         s->rwstate=SSL_WRITING;
578                         if (BIO_flush(s->wbio) <= 0)
579                                 {
580                                 ret= -1;
581                                 goto end;
582                                 }
583                         s->rwstate=SSL_NOTHING;
584                         s->state=s->s3->tmp.next_state;
585                         break;
586
587                 case SSL_ST_OK:
588                         /* clean a few things up */
589                         ssl3_cleanup_key_block(s);
590
591                         if (s->init_buf != NULL)
592                                 {
593                                 BUF_MEM_free(s->init_buf);
594                                 s->init_buf=NULL;
595                                 }
596
597                         /* If we are not 'joining' the last two packets,
598                          * remove the buffering now */
599                         if (!(s->s3->flags & SSL3_FLAGS_POP_BUFFER))
600                                 ssl_free_wbio_buffer(s);
601                         /* else do it later in ssl3_write */
602
603                         s->init_num=0;
604                         s->renegotiate=0;
605                         s->new_session=0;
606
607                         ssl_update_cache(s,SSL_SESS_CACHE_CLIENT);
608                         if (s->hit) s->ctx->stats.sess_hit++;
609
610                         ret=1;
611                         /* s->server=0; */
612                         s->handshake_func=ssl3_connect;
613                         s->ctx->stats.sess_connect_good++;
614
615                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
616
617                         goto end;
618                         /* break; */
619                         
620                 default:
621                         SSLerr(SSL_F_SSL3_CONNECT,SSL_R_UNKNOWN_STATE);
622                         ret= -1;
623                         goto end;
624                         /* break; */
625                         }
626
627                 /* did we do anything */
628                 if (!s->s3->tmp.reuse_message && !skip)
629                         {
630                         if (s->debug)
631                                 {
632                                 if ((ret=BIO_flush(s->wbio)) <= 0)
633                                         goto end;
634                                 }
635
636                         if ((cb != NULL) && (s->state != state))
637                                 {
638                                 new_state=s->state;
639                                 s->state=state;
640                                 cb(s,SSL_CB_CONNECT_LOOP,1);
641                                 s->state=new_state;
642                                 }
643                         }
644                 skip=0;
645                 }
646 end:
647         s->in_handshake--;
648         if (buf != NULL)
649                 BUF_MEM_free(buf);
650         if (cb != NULL)
651                 cb(s,SSL_CB_CONNECT_EXIT,ret);
652         return(ret);
653         }
654
655
656 int ssl3_client_hello(SSL *s)
657         {
658         unsigned char *buf;
659         unsigned char *p,*d;
660         int i;
661         unsigned long l;
662 #ifndef OPENSSL_NO_COMP
663         int j;
664         SSL_COMP *comp;
665 #endif
666
667         buf=(unsigned char *)s->init_buf->data;
668         if (s->state == SSL3_ST_CW_CLNT_HELLO_A)
669                 {
670                 SSL_SESSION *sess = s->session;
671                 if ((sess == NULL) ||
672                         (sess->ssl_version != s->version) ||
673 #ifdef OPENSSL_NO_TLSEXT
674                         !sess->session_id_length ||
675 #else
676                         (!sess->session_id_length && !sess->tlsext_tick) ||
677 #endif
678                         (sess->not_resumable))
679                         {
680                         if (!ssl_get_new_session(s,0))
681                                 goto err;
682                         }
683                 /* else use the pre-loaded session */
684
685                 p=s->s3->client_random;
686
687                 if (ssl_fill_hello_random(s, 0, p, SSL3_RANDOM_SIZE) <= 0)
688                         goto err;
689
690                 /* Do the message type and length last */
691                 d=p= &(buf[4]);
692
693                 /* version indicates the negotiated version: for example from
694                  * an SSLv2/v3 compatible client hello). The client_version
695                  * field is the maximum version we permit and it is also
696                  * used in RSA encrypted premaster secrets. Some servers can
697                  * choke if we initially report a higher version then
698                  * renegotiate to a lower one in the premaster secret. This
699                  * didn't happen with TLS 1.0 as most servers supported it
700                  * but it can with TLS 1.1 or later if the server only supports
701                  * 1.0.
702                  *
703                  * Possible scenario with previous logic:
704                  *      1. Client hello indicates TLS 1.2
705                  *      2. Server hello says TLS 1.0
706                  *      3. RSA encrypted premaster secret uses 1.2.
707                  *      4. Handhaked proceeds using TLS 1.0.
708                  *      5. Server sends hello request to renegotiate.
709                  *      6. Client hello indicates TLS v1.0 as we now
710                  *         know that is maximum server supports.
711                  *      7. Server chokes on RSA encrypted premaster secret
712                  *         containing version 1.0.
713                  *
714                  * For interoperability it should be OK to always use the
715                  * maximum version we support in client hello and then rely
716                  * on the checking of version to ensure the servers isn't
717                  * being inconsistent: for example initially negotiating with
718                  * TLS 1.0 and renegotiating with TLS 1.2. We do this by using
719                  * client_version in client hello and not resetting it to
720                  * the negotiated version.
721                  */
722 #if 0
723                 *(p++)=s->version>>8;
724                 *(p++)=s->version&0xff;
725                 s->client_version=s->version;
726 #else
727                 *(p++)=s->client_version>>8;
728                 *(p++)=s->client_version&0xff;
729 #endif
730
731                 /* Random stuff */
732                 memcpy(p,s->s3->client_random,SSL3_RANDOM_SIZE);
733                 p+=SSL3_RANDOM_SIZE;
734
735                 /* Session ID */
736                 if (s->new_session)
737                         i=0;
738                 else
739                         i=s->session->session_id_length;
740                 *(p++)=i;
741                 if (i != 0)
742                         {
743                         if (i > (int)sizeof(s->session->session_id))
744                                 {
745                                 SSLerr(SSL_F_SSL3_CLIENT_HELLO, ERR_R_INTERNAL_ERROR);
746                                 goto err;
747                                 }
748                         memcpy(p,s->session->session_id,i);
749                         p+=i;
750                         }
751                 
752                 /* Ciphers supported */
753                 i=ssl_cipher_list_to_bytes(s,SSL_get_ciphers(s),&(p[2]),0);
754                 if (i == 0)
755                         {
756                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_NO_CIPHERS_AVAILABLE);
757                         goto err;
758                         }
759 #ifdef OPENSSL_MAX_TLS1_2_CIPHER_LENGTH
760                         /* Some servers hang if client hello > 256 bytes
761                          * as hack workaround chop number of supported ciphers
762                          * to keep it well below this if we use TLS v1.2
763                          */
764                         if (TLS1_get_version(s) >= TLS1_2_VERSION
765                                 && i > OPENSSL_MAX_TLS1_2_CIPHER_LENGTH)
766                                 i = OPENSSL_MAX_TLS1_2_CIPHER_LENGTH & ~1;
767 #endif
768                 s2n(i,p);
769                 p+=i;
770
771                 /* COMPRESSION */
772 #ifdef OPENSSL_NO_COMP
773                 *(p++)=1;
774 #else
775
776                 if ((s->options & SSL_OP_NO_COMPRESSION)
777                                         || !s->ctx->comp_methods)
778                         j=0;
779                 else
780                         j=sk_SSL_COMP_num(s->ctx->comp_methods);
781                 *(p++)=1+j;
782                 for (i=0; i<j; i++)
783                         {
784                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,i);
785                         *(p++)=comp->id;
786                         }
787 #endif
788                 *(p++)=0; /* Add the NULL method */
789
790 #ifndef OPENSSL_NO_TLSEXT
791                 /* TLS extensions*/
792                 if (ssl_prepare_clienthello_tlsext(s) <= 0)
793                         {
794                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
795                         goto err;
796                         }
797                 if ((p = ssl_add_clienthello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
798                         {
799                         SSLerr(SSL_F_SSL3_CLIENT_HELLO,ERR_R_INTERNAL_ERROR);
800                         goto err;
801                         }
802 #endif
803                 
804                 l=(p-d);
805                 d=buf;
806                 *(d++)=SSL3_MT_CLIENT_HELLO;
807                 l2n3(l,d);
808
809                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
810                 /* number of bytes to write */
811                 s->init_num=p-buf;
812                 s->init_off=0;
813                 }
814
815         /* SSL3_ST_CW_CLNT_HELLO_B */
816         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
817 err:
818         return(-1);
819         }
820
821 int ssl3_get_server_hello(SSL *s)
822         {
823         STACK_OF(SSL_CIPHER) *sk;
824         const SSL_CIPHER *c;
825         unsigned char *p,*d;
826         int i,al,ok;
827         unsigned int j;
828         long n;
829 #ifndef OPENSSL_NO_COMP
830         SSL_COMP *comp;
831 #endif
832
833         n=s->method->ssl_get_message(s,
834                 SSL3_ST_CR_SRVR_HELLO_A,
835                 SSL3_ST_CR_SRVR_HELLO_B,
836                 -1,
837                 20000, /* ?? */
838                 &ok);
839
840         if (!ok) return((int)n);
841
842         if ( SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER)
843                 {
844                 if ( s->s3->tmp.message_type == DTLS1_MT_HELLO_VERIFY_REQUEST)
845                         {
846                         if ( s->d1->send_cookie == 0)
847                                 {
848                                 s->s3->tmp.reuse_message = 1;
849                                 return 1;
850                                 }
851                         else /* already sent a cookie */
852                                 {
853                                 al=SSL_AD_UNEXPECTED_MESSAGE;
854                                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
855                                 goto f_err;
856                                 }
857                         }
858                 }
859         
860         if ( s->s3->tmp.message_type != SSL3_MT_SERVER_HELLO)
861                 {
862                 al=SSL_AD_UNEXPECTED_MESSAGE;
863                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_MESSAGE_TYPE);
864                 goto f_err;
865                 }
866
867         d=p=(unsigned char *)s->init_msg;
868
869         if ((p[0] != (s->version>>8)) || (p[1] != (s->version&0xff)))
870                 {
871                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_SSL_VERSION);
872                 s->version=(s->version&0xff00)|p[1];
873                 al=SSL_AD_PROTOCOL_VERSION;
874                 goto f_err;
875                 }
876         p+=2;
877
878         /* load the server hello data */
879         /* load the server random */
880         memcpy(s->s3->server_random,p,SSL3_RANDOM_SIZE);
881         p+=SSL3_RANDOM_SIZE;
882
883         s->hit = 0;
884
885         /* get the session-id */
886         j= *(p++);
887
888         if ((j > sizeof s->session->session_id) || (j > SSL3_SESSION_ID_SIZE))
889                 {
890                 al=SSL_AD_ILLEGAL_PARAMETER;
891                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SSL3_SESSION_ID_TOO_LONG);
892                 goto f_err;
893                 }
894
895 #ifndef OPENSSL_NO_TLSEXT
896         /* check if we want to resume the session based on external pre-shared secret */
897         if (s->version >= TLS1_VERSION && s->tls_session_secret_cb)
898                 {
899                 SSL_CIPHER *pref_cipher=NULL;
900                 s->session->master_key_length=sizeof(s->session->master_key);
901                 if (s->tls_session_secret_cb(s, s->session->master_key,
902                                              &s->session->master_key_length,
903                                              NULL, &pref_cipher,
904                                              s->tls_session_secret_cb_arg))
905                         {
906                         s->session->cipher = pref_cipher ?
907                                 pref_cipher : ssl_get_cipher_by_char(s, p+j);
908                         s->hit = 1;
909                         s->s3->flags |= SSL3_FLAGS_CCS_OK;
910                         }
911                 }
912 #endif /* OPENSSL_NO_TLSEXT */
913
914         if (!s->hit && j != 0 && j == s->session->session_id_length
915             && memcmp(p,s->session->session_id,j) == 0)
916             {
917             if(s->sid_ctx_length != s->session->sid_ctx_length
918                || memcmp(s->session->sid_ctx,s->sid_ctx,s->sid_ctx_length))
919                 {
920                 /* actually a client application bug */
921                 al=SSL_AD_ILLEGAL_PARAMETER;
922                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_ATTEMPT_TO_REUSE_SESSION_IN_DIFFERENT_CONTEXT);
923                 goto f_err;
924                 }
925             s->s3->flags |= SSL3_FLAGS_CCS_OK;
926             s->hit=1;
927             }
928         /* a miss or crap from the other end */
929         if (!s->hit)
930                 {
931                 /* If we were trying for session-id reuse, make a new
932                  * SSL_SESSION so we don't stuff up other people */
933                 if (s->session->session_id_length > 0)
934                         {
935                         if (!ssl_get_new_session(s,0))
936                                 {
937                                 al=SSL_AD_INTERNAL_ERROR;
938                                 goto f_err;
939                                 }
940                         }
941                 s->session->session_id_length=j;
942                 memcpy(s->session->session_id,p,j); /* j could be 0 */
943                 }
944         p+=j;
945         c=ssl_get_cipher_by_char(s,p);
946         if (c == NULL)
947                 {
948                 /* unknown cipher */
949                 al=SSL_AD_ILLEGAL_PARAMETER;
950                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNKNOWN_CIPHER_RETURNED);
951                 goto f_err;
952                 }
953         /* TLS v1.2 only ciphersuites require v1.2 or later */
954         if ((c->algorithm_ssl & SSL_TLSV1_2) && 
955                 (TLS1_get_version(s) < TLS1_2_VERSION))
956                 {
957                 al=SSL_AD_ILLEGAL_PARAMETER;
958                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
959                 goto f_err;
960                 }
961 #ifndef OPENSSL_NO_SRP
962         if (((c->algorithm_mkey & SSL_kSRP) || (c->algorithm_auth & SSL_aSRP)) &&
963                     !(s->srp_ctx.srp_Mask & SSL_kSRP))
964                 {
965                 al=SSL_AD_ILLEGAL_PARAMETER;
966                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
967                 goto f_err;
968                 }
969 #endif /* OPENSSL_NO_SRP */
970         p+=ssl_put_cipher_by_char(s,NULL,NULL);
971
972         sk=ssl_get_ciphers_by_id(s);
973         i=sk_SSL_CIPHER_find(sk,c);
974         if (i < 0)
975                 {
976                 /* we did not say we would use this cipher */
977                 al=SSL_AD_ILLEGAL_PARAMETER;
978                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_WRONG_CIPHER_RETURNED);
979                 goto f_err;
980                 }
981
982         /* Depending on the session caching (internal/external), the cipher
983            and/or cipher_id values may not be set. Make sure that
984            cipher_id is set and use it for comparison. */
985         if (s->session->cipher)
986                 s->session->cipher_id = s->session->cipher->id;
987         if (s->hit && (s->session->cipher_id != c->id))
988                 {
989 /* Workaround is now obsolete */
990 #if 0
991                 if (!(s->options &
992                         SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG))
993 #endif
994                         {
995                         al=SSL_AD_ILLEGAL_PARAMETER;
996                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_CIPHER_NOT_RETURNED);
997                         goto f_err;
998                         }
999                 }
1000         s->s3->tmp.new_cipher=c;
1001         /* Don't digest cached records if TLS v1.2: we may need them for
1002          * client authentication.
1003          */
1004         if (TLS1_get_version(s) < TLS1_2_VERSION && !ssl3_digest_cached_records(s))
1005                 {
1006                 al = SSL_AD_INTERNAL_ERROR;
1007                 goto f_err;
1008                 }
1009         /* lets get the compression algorithm */
1010         /* COMPRESSION */
1011 #ifdef OPENSSL_NO_COMP
1012         if (*(p++) != 0)
1013                 {
1014                 al=SSL_AD_ILLEGAL_PARAMETER;
1015                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1016                 goto f_err;
1017                 }
1018         /* If compression is disabled we'd better not try to resume a session
1019          * using compression.
1020          */
1021         if (s->session->compress_meth != 0)
1022                 {
1023                 al=SSL_AD_INTERNAL_ERROR;
1024                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1025                 goto f_err;
1026                 }
1027 #else
1028         j= *(p++);
1029         if (s->hit && j != s->session->compress_meth)
1030                 {
1031                 al=SSL_AD_ILLEGAL_PARAMETER;
1032                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_OLD_SESSION_COMPRESSION_ALGORITHM_NOT_RETURNED);
1033                 goto f_err;
1034                 }
1035         if (j == 0)
1036                 comp=NULL;
1037         else if (s->options & SSL_OP_NO_COMPRESSION)
1038                 {
1039                 al=SSL_AD_ILLEGAL_PARAMETER;
1040                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_COMPRESSION_DISABLED);
1041                 goto f_err;
1042                 }
1043         else
1044                 comp=ssl3_comp_find(s->ctx->comp_methods,j);
1045         
1046         if ((j != 0) && (comp == NULL))
1047                 {
1048                 al=SSL_AD_ILLEGAL_PARAMETER;
1049                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_UNSUPPORTED_COMPRESSION_ALGORITHM);
1050                 goto f_err;
1051                 }
1052         else
1053                 {
1054                 s->s3->tmp.new_compression=comp;
1055                 }
1056 #endif
1057
1058 #ifndef OPENSSL_NO_TLSEXT
1059         /* TLS extensions*/
1060         if (s->version >= SSL3_VERSION)
1061                 {
1062                 if (!ssl_parse_serverhello_tlsext(s,&p,d,n, &al))
1063                         {
1064                         /* 'al' set by ssl_parse_serverhello_tlsext */
1065                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_PARSE_TLSEXT);
1066                         goto f_err; 
1067                         }
1068                 if (ssl_check_serverhello_tlsext(s) <= 0)
1069                         {
1070                         SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1071                                 goto err;
1072                         }
1073                 }
1074 #endif
1075
1076         if (p != (d+n))
1077                 {
1078                 /* wrong packet length */
1079                 al=SSL_AD_DECODE_ERROR;
1080                 SSLerr(SSL_F_SSL3_GET_SERVER_HELLO,SSL_R_BAD_PACKET_LENGTH);
1081                 goto f_err;
1082                 }
1083
1084         return(1);
1085 f_err:
1086         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1087 err:
1088         return(-1);
1089         }
1090
1091 int ssl3_get_server_certificate(SSL *s)
1092         {
1093         int al,i,ok,ret= -1;
1094         unsigned long n,nc,llen,l;
1095         X509 *x=NULL;
1096         const unsigned char *q,*p;
1097         unsigned char *d;
1098         STACK_OF(X509) *sk=NULL;
1099         SESS_CERT *sc;
1100         EVP_PKEY *pkey=NULL;
1101         int need_cert = 1; /* VRS: 0=> will allow null cert if auth == KRB5 */
1102
1103         n=s->method->ssl_get_message(s,
1104                 SSL3_ST_CR_CERT_A,
1105                 SSL3_ST_CR_CERT_B,
1106                 -1,
1107                 s->max_cert_list,
1108                 &ok);
1109
1110         if (!ok) return((int)n);
1111
1112         if ((s->s3->tmp.message_type == SSL3_MT_SERVER_KEY_EXCHANGE) ||
1113                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5) && 
1114                 (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)))
1115                 {
1116                 s->s3->tmp.reuse_message=1;
1117                 return(1);
1118                 }
1119
1120         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
1121                 {
1122                 al=SSL_AD_UNEXPECTED_MESSAGE;
1123                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_BAD_MESSAGE_TYPE);
1124                 goto f_err;
1125                 }
1126         p=d=(unsigned char *)s->init_msg;
1127
1128         if ((sk=sk_X509_new_null()) == NULL)
1129                 {
1130                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1131                 goto err;
1132                 }
1133
1134         n2l3(p,llen);
1135         if (llen+3 != n)
1136                 {
1137                 al=SSL_AD_DECODE_ERROR;
1138                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
1139                 goto f_err;
1140                 }
1141         for (nc=0; nc<llen; )
1142                 {
1143                 n2l3(p,l);
1144                 if ((l+nc+3) > llen)
1145                         {
1146                         al=SSL_AD_DECODE_ERROR;
1147                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1148                         goto f_err;
1149                         }
1150
1151                 q=p;
1152                 x=d2i_X509(NULL,&q,l);
1153                 if (x == NULL)
1154                         {
1155                         al=SSL_AD_BAD_CERTIFICATE;
1156                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_ASN1_LIB);
1157                         goto f_err;
1158                         }
1159                 if (q != (p+l))
1160                         {
1161                         al=SSL_AD_DECODE_ERROR;
1162                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
1163                         goto f_err;
1164                         }
1165                 if (!sk_X509_push(sk,x))
1166                         {
1167                         SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,ERR_R_MALLOC_FAILURE);
1168                         goto err;
1169                         }
1170                 x=NULL;
1171                 nc+=l+3;
1172                 p=q;
1173                 }
1174
1175         i=ssl_verify_cert_chain(s,sk);
1176         if ((s->verify_mode != SSL_VERIFY_NONE) && (i <= 0)
1177 #ifndef OPENSSL_NO_KRB5
1178             && !((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1179                  (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1180 #endif /* OPENSSL_NO_KRB5 */
1181                 )
1182                 {
1183                 al=ssl_verify_alarm_type(s->verify_result);
1184                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
1185                 goto f_err; 
1186                 }
1187         ERR_clear_error(); /* but we keep s->verify_result */
1188
1189         sc=ssl_sess_cert_new();
1190         if (sc == NULL) goto err;
1191
1192         if (s->session->sess_cert) ssl_sess_cert_free(s->session->sess_cert);
1193         s->session->sess_cert=sc;
1194
1195         sc->cert_chain=sk;
1196         /* Inconsistency alert: cert_chain does include the peer's
1197          * certificate, which we don't include in s3_srvr.c */
1198         x=sk_X509_value(sk,0);
1199         sk=NULL;
1200         /* VRS 19990621: possible memory leak; sk=null ==> !sk_pop_free() @end*/
1201
1202         pkey=X509_get_pubkey(x);
1203
1204         /* VRS: allow null cert if auth == KRB5 */
1205         need_cert = ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5) &&
1206                     (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
1207                     ? 0 : 1;
1208
1209 #ifdef KSSL_DEBUG
1210         printf("pkey,x = %p, %p\n", pkey,x);
1211         printf("ssl_cert_type(x,pkey) = %d\n", ssl_cert_type(x,pkey));
1212         printf("cipher, alg, nc = %s, %lx, %lx, %d\n", s->s3->tmp.new_cipher->name,
1213                 s->s3->tmp.new_cipher->algorithm_mkey, s->s3->tmp.new_cipher->algorithm_auth, need_cert);
1214 #endif    /* KSSL_DEBUG */
1215
1216         if (need_cert && ((pkey == NULL) || EVP_PKEY_missing_parameters(pkey)))
1217                 {
1218                 x=NULL;
1219                 al=SSL3_AL_FATAL;
1220                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1221                         SSL_R_UNABLE_TO_FIND_PUBLIC_KEY_PARAMETERS);
1222                 goto f_err;
1223                 }
1224
1225         i=ssl_cert_type(x,pkey);
1226         if (need_cert && i < 0)
1227                 {
1228                 x=NULL;
1229                 al=SSL3_AL_FATAL;
1230                 SSLerr(SSL_F_SSL3_GET_SERVER_CERTIFICATE,
1231                         SSL_R_UNKNOWN_CERTIFICATE_TYPE);
1232                 goto f_err;
1233                 }
1234
1235         if (need_cert)
1236                 {
1237                 sc->peer_cert_type=i;
1238                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1239                 /* Why would the following ever happen?
1240                  * We just created sc a couple of lines ago. */
1241                 if (sc->peer_pkeys[i].x509 != NULL)
1242                         X509_free(sc->peer_pkeys[i].x509);
1243                 sc->peer_pkeys[i].x509=x;
1244                 sc->peer_key= &(sc->peer_pkeys[i]);
1245
1246                 if (s->session->peer != NULL)
1247                         X509_free(s->session->peer);
1248                 CRYPTO_add(&x->references,1,CRYPTO_LOCK_X509);
1249                 s->session->peer=x;
1250                 }
1251         else
1252                 {
1253                 sc->peer_cert_type=i;
1254                 sc->peer_key= NULL;
1255
1256                 if (s->session->peer != NULL)
1257                         X509_free(s->session->peer);
1258                 s->session->peer=NULL;
1259                 }
1260         s->session->verify_result = s->verify_result;
1261
1262         x=NULL;
1263         ret=1;
1264
1265         if (0)
1266                 {
1267 f_err:
1268                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1269                 }
1270 err:
1271         EVP_PKEY_free(pkey);
1272         X509_free(x);
1273         sk_X509_pop_free(sk,X509_free);
1274         return(ret);
1275         }
1276
1277 int ssl3_get_key_exchange(SSL *s)
1278         {
1279 #ifndef OPENSSL_NO_RSA
1280         unsigned char *q,md_buf[EVP_MAX_MD_SIZE*2];
1281 #endif
1282         EVP_MD_CTX md_ctx;
1283         unsigned char *param,*p;
1284         int al,j,ok;
1285         long i,param_len,n,alg_k,alg_a;
1286         EVP_PKEY *pkey=NULL;
1287         const EVP_MD *md = NULL;
1288 #ifndef OPENSSL_NO_RSA
1289         RSA *rsa=NULL;
1290 #endif
1291 #ifndef OPENSSL_NO_DH
1292         DH *dh=NULL;
1293 #endif
1294 #ifndef OPENSSL_NO_ECDH
1295         EC_KEY *ecdh = NULL;
1296         BN_CTX *bn_ctx = NULL;
1297         EC_POINT *srvr_ecpoint = NULL;
1298         int curve_nid = 0;
1299         int encoded_pt_len = 0;
1300 #endif
1301
1302         /* use same message size as in ssl3_get_certificate_request()
1303          * as ServerKeyExchange message may be skipped */
1304         n=s->method->ssl_get_message(s,
1305                 SSL3_ST_CR_KEY_EXCH_A,
1306                 SSL3_ST_CR_KEY_EXCH_B,
1307                 -1,
1308                 s->max_cert_list,
1309                 &ok);
1310         if (!ok) return((int)n);
1311
1312         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1313                 {
1314 #ifndef OPENSSL_NO_PSK
1315                 /* In plain PSK ciphersuite, ServerKeyExchange can be
1316                    omitted if no identity hint is sent. Set
1317                    session->sess_cert anyway to avoid problems
1318                    later.*/
1319                 if (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
1320                         {
1321                         s->session->sess_cert=ssl_sess_cert_new();
1322                         if (s->ctx->psk_identity_hint)
1323                                 OPENSSL_free(s->ctx->psk_identity_hint);
1324                         s->ctx->psk_identity_hint = NULL;
1325                         }
1326 #endif
1327                 s->s3->tmp.reuse_message=1;
1328                 return(1);
1329                 }
1330
1331         param=p=(unsigned char *)s->init_msg;
1332         if (s->session->sess_cert != NULL)
1333                 {
1334 #ifndef OPENSSL_NO_RSA
1335                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1336                         {
1337                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
1338                         s->session->sess_cert->peer_rsa_tmp=NULL;
1339                         }
1340 #endif
1341 #ifndef OPENSSL_NO_DH
1342                 if (s->session->sess_cert->peer_dh_tmp)
1343                         {
1344                         DH_free(s->session->sess_cert->peer_dh_tmp);
1345                         s->session->sess_cert->peer_dh_tmp=NULL;
1346                         }
1347 #endif
1348 #ifndef OPENSSL_NO_ECDH
1349                 if (s->session->sess_cert->peer_ecdh_tmp)
1350                         {
1351                         EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1352                         s->session->sess_cert->peer_ecdh_tmp=NULL;
1353                         }
1354 #endif
1355                 }
1356         else
1357                 {
1358                 s->session->sess_cert=ssl_sess_cert_new();
1359                 }
1360
1361         /* Total length of the parameters including the length prefix */
1362         param_len=0;
1363
1364         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
1365         alg_a=s->s3->tmp.new_cipher->algorithm_auth;
1366         EVP_MD_CTX_init(&md_ctx);
1367
1368         al=SSL_AD_DECODE_ERROR;
1369
1370 #ifndef OPENSSL_NO_PSK
1371         if (alg_k & SSL_kPSK)
1372                 {
1373                 char tmp_id_hint[PSK_MAX_IDENTITY_LEN+1];
1374
1375                 param_len = 2;
1376                 if (param_len > n)
1377                         {
1378                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1379                                 SSL_R_LENGTH_TOO_SHORT);
1380                         goto f_err;
1381                         }
1382                 n2s(p,i);
1383
1384                 /* Store PSK identity hint for later use, hint is used
1385                  * in ssl3_send_client_key_exchange.  Assume that the
1386                  * maximum length of a PSK identity hint can be as
1387                  * long as the maximum length of a PSK identity. */
1388                 if (i > PSK_MAX_IDENTITY_LEN)
1389                         {
1390                         al=SSL_AD_HANDSHAKE_FAILURE;
1391                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1392                                 SSL_R_DATA_LENGTH_TOO_LONG);
1393                         goto f_err;
1394                         }
1395                 if (i > n - param_len)
1396                         {
1397                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1398                                 SSL_R_BAD_PSK_IDENTITY_HINT_LENGTH);
1399                         goto f_err;
1400                         }
1401                 param_len += i;
1402
1403                 /* If received PSK identity hint contains NULL
1404                  * characters, the hint is truncated from the first
1405                  * NULL. p may not be ending with NULL, so create a
1406                  * NULL-terminated string. */
1407                 memcpy(tmp_id_hint, p, i);
1408                 memset(tmp_id_hint+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
1409                 if (s->ctx->psk_identity_hint != NULL)
1410                         OPENSSL_free(s->ctx->psk_identity_hint);
1411                 s->ctx->psk_identity_hint = BUF_strdup(tmp_id_hint);
1412                 if (s->ctx->psk_identity_hint == NULL)
1413                         {
1414                         al=SSL_AD_HANDSHAKE_FAILURE;
1415                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE, ERR_R_MALLOC_FAILURE);
1416                         goto f_err;
1417                         }          
1418
1419                 p+=i;
1420                 n-=param_len;
1421                 }
1422         else
1423 #endif /* !OPENSSL_NO_PSK */
1424 #ifndef OPENSSL_NO_SRP
1425         if (alg_k & SSL_kSRP)
1426                 {
1427                 param_len = 2;
1428                 if (param_len > n)
1429                         {
1430                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1431                                 SSL_R_LENGTH_TOO_SHORT);
1432                         goto f_err;
1433                         }
1434                 n2s(p,i);
1435
1436                 if (i > n - param_len)
1437                         {
1438                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_N_LENGTH);
1439                         goto f_err;
1440                         }
1441                 param_len += i;
1442
1443                 if (!(s->srp_ctx.N=BN_bin2bn(p,i,NULL)))
1444                         {
1445                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1446                         goto err;
1447                         }
1448                 p+=i;
1449
1450
1451                 if (2 > n - param_len)
1452                         {
1453                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1454                                 SSL_R_LENGTH_TOO_SHORT);
1455                         goto f_err;
1456                         }
1457                 param_len += 2;
1458
1459                 n2s(p,i);
1460
1461                 if (i > n - param_len)
1462                         {
1463                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_G_LENGTH);
1464                         goto f_err;
1465                         }
1466                 param_len += i;
1467
1468                 if (!(s->srp_ctx.g=BN_bin2bn(p,i,NULL)))
1469                         {
1470                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1471                         goto err;
1472                         }
1473                 p+=i;
1474
1475
1476                 if (1 > n - param_len)
1477                         {
1478                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1479                                 SSL_R_LENGTH_TOO_SHORT);
1480                         goto f_err;
1481                         }
1482                 param_len += 1;
1483
1484                 i = (unsigned int)(p[0]);
1485                 p++;
1486
1487                 if (i > n - param_len)
1488                         {
1489                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_S_LENGTH);
1490                         goto f_err;
1491                         }
1492                 param_len += i;
1493
1494                 if (!(s->srp_ctx.s=BN_bin2bn(p,i,NULL)))
1495                         {
1496                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1497                         goto err;
1498                         }
1499                 p+=i;
1500
1501                 if (2 > n - param_len)
1502                         {
1503                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1504                                 SSL_R_LENGTH_TOO_SHORT);
1505                         goto f_err;
1506                         }
1507                 param_len += 2;
1508
1509                 n2s(p,i);
1510
1511                 if (i > n - param_len)
1512                         {
1513                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_B_LENGTH);
1514                         goto f_err;
1515                         }
1516                 param_len += i;
1517
1518                 if (!(s->srp_ctx.B=BN_bin2bn(p,i,NULL)))
1519                         {
1520                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1521                         goto err;
1522                         }
1523                 p+=i;
1524                 n-=param_len;
1525
1526                 if (!srp_verify_server_param(s, &al))
1527                         {
1528                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
1529                         goto f_err;
1530                         }
1531
1532 /* We must check if there is a certificate */
1533 #ifndef OPENSSL_NO_RSA
1534                 if (alg_a & SSL_aRSA)
1535                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1536 #else
1537                 if (0)
1538                         ;
1539 #endif
1540 #ifndef OPENSSL_NO_DSA
1541                 else if (alg_a & SSL_aDSS)
1542                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1543 #endif
1544                 }
1545         else
1546 #endif /* !OPENSSL_NO_SRP */
1547 #ifndef OPENSSL_NO_RSA
1548         if (alg_k & SSL_kRSA)
1549                 {
1550                 if ((rsa=RSA_new()) == NULL)
1551                         {
1552                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1553                         goto err;
1554                         }
1555
1556                 param_len = 2;
1557                 if (param_len > n)
1558                         {
1559                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1560                                 SSL_R_LENGTH_TOO_SHORT);
1561                         goto f_err;
1562                         }
1563                 n2s(p,i);
1564
1565                 if (i > n - param_len)
1566                         {
1567                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1568                         goto f_err;
1569                         }
1570                 param_len += i;
1571
1572                 if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1573                         {
1574                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1575                         goto err;
1576                         }
1577                 p+=i;
1578
1579                 if (2 > n - param_len)
1580                         {
1581                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1582                                 SSL_R_LENGTH_TOO_SHORT);
1583                         goto f_err;
1584                         }
1585                 param_len += 2;
1586
1587                 n2s(p,i);
1588
1589                 if (i > n - param_len)
1590                         {
1591                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1592                         goto f_err;
1593                         }
1594                 param_len += i;
1595
1596                 if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1597                         {
1598                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1599                         goto err;
1600                         }
1601                 p+=i;
1602                 n-=param_len;
1603
1604                 /* this should be because we are using an export cipher */
1605                 if (alg_a & SSL_aRSA)
1606                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1607                 else
1608                         {
1609                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1610                         goto err;
1611                         }
1612                 s->session->sess_cert->peer_rsa_tmp=rsa;
1613                 rsa=NULL;
1614                 }
1615 #else /* OPENSSL_NO_RSA */
1616         if (0)
1617                 ;
1618 #endif
1619 #ifndef OPENSSL_NO_DH
1620         else if (alg_k & SSL_kEDH)
1621                 {
1622                 if ((dh=DH_new()) == NULL)
1623                         {
1624                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1625                         goto err;
1626                         }
1627
1628                 param_len = 2;
1629                 if (param_len > n)
1630                         {
1631                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1632                                 SSL_R_LENGTH_TOO_SHORT);
1633                         goto f_err;
1634                         }
1635                 n2s(p,i);
1636
1637                 if (i > n - param_len)
1638                         {
1639                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1640                         goto f_err;
1641                         }
1642                 param_len += i;
1643
1644                 if (!(dh->p=BN_bin2bn(p,i,NULL)))
1645                         {
1646                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1647                         goto err;
1648                         }
1649                 p+=i;
1650
1651                 if (2 > n - param_len)
1652                         {
1653                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1654                                 SSL_R_LENGTH_TOO_SHORT);
1655                         goto f_err;
1656                         }
1657                 param_len += 2;
1658
1659                 n2s(p,i);
1660
1661                 if (i > n - param_len)
1662                         {
1663                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1664                         goto f_err;
1665                         }
1666                 param_len += i;
1667
1668                 if (!(dh->g=BN_bin2bn(p,i,NULL)))
1669                         {
1670                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1671                         goto err;
1672                         }
1673                 p+=i;
1674
1675                 if (2 > n - param_len)
1676                         {
1677                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1678                                 SSL_R_LENGTH_TOO_SHORT);
1679                         goto f_err;
1680                         }
1681                 param_len += 2;
1682
1683                 n2s(p,i);
1684
1685                 if (i > n - param_len)
1686                         {
1687                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1688                         goto f_err;
1689                         }
1690                 param_len += i;
1691
1692                 if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1693                         {
1694                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1695                         goto err;
1696                         }
1697                 p+=i;
1698                 n-=param_len;
1699
1700 #ifndef OPENSSL_NO_RSA
1701                 if (alg_a & SSL_aRSA)
1702                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1703 #else
1704                 if (0)
1705                         ;
1706 #endif
1707 #ifndef OPENSSL_NO_DSA
1708                 else if (alg_a & SSL_aDSS)
1709                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1710 #endif
1711                 /* else anonymous DH, so no certificate or pkey. */
1712
1713                 s->session->sess_cert->peer_dh_tmp=dh;
1714                 dh=NULL;
1715                 }
1716         else if ((alg_k & SSL_kDHr) || (alg_k & SSL_kDHd))
1717                 {
1718                 al=SSL_AD_ILLEGAL_PARAMETER;
1719                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1720                 goto f_err;
1721                 }
1722 #endif /* !OPENSSL_NO_DH */
1723
1724 #ifndef OPENSSL_NO_ECDH
1725         else if (alg_k & SSL_kEECDH)
1726                 {
1727                 EC_GROUP *ngroup;
1728                 const EC_GROUP *group;
1729
1730                 if ((ecdh=EC_KEY_new()) == NULL)
1731                         {
1732                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1733                         goto err;
1734                         }
1735
1736                 /* Extract elliptic curve parameters and the
1737                  * server's ephemeral ECDH public key.
1738                  * Keep accumulating lengths of various components in
1739                  * param_len and make sure it never exceeds n.
1740                  */
1741
1742                 /* XXX: For now we only support named (not generic) curves
1743                  * and the ECParameters in this case is just three bytes. We
1744                  * also need one byte for the length of the encoded point
1745                  */
1746                 param_len=4;
1747                 if (param_len > n)
1748                         {
1749                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1750                                 SSL_R_LENGTH_TOO_SHORT);
1751                         goto f_err;
1752                         }
1753
1754                 if ((*p != NAMED_CURVE_TYPE) || 
1755                     ((curve_nid = tls1_ec_curve_id2nid(*(p + 2))) == 0))
1756                         {
1757                         al=SSL_AD_INTERNAL_ERROR;
1758                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1759                         goto f_err;
1760                         }
1761
1762                 ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1763                 if (ngroup == NULL)
1764                         {
1765                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1766                         goto err;
1767                         }
1768                 if (EC_KEY_set_group(ecdh, ngroup) == 0)
1769                         {
1770                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1771                         goto err;
1772                         }
1773                 EC_GROUP_free(ngroup);
1774
1775                 group = EC_KEY_get0_group(ecdh);
1776
1777                 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1778                     (EC_GROUP_get_degree(group) > 163))
1779                         {
1780                         al=SSL_AD_EXPORT_RESTRICTION;
1781                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1782                         goto f_err;
1783                         }
1784
1785                 p+=3;
1786
1787                 /* Next, get the encoded ECPoint */
1788                 if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1789                     ((bn_ctx = BN_CTX_new()) == NULL))
1790                         {
1791                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1792                         goto err;
1793                         }
1794
1795                 encoded_pt_len = *p;  /* length of encoded point */
1796                 p+=1;
1797
1798                 if ((encoded_pt_len > n - param_len) ||
1799                     (EC_POINT_oct2point(group, srvr_ecpoint, 
1800                         p, encoded_pt_len, bn_ctx) == 0))
1801                         {
1802                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
1803                         goto f_err;
1804                         }
1805                 param_len += encoded_pt_len;
1806
1807                 n-=param_len;
1808                 p+=encoded_pt_len;
1809
1810                 /* The ECC/TLS specification does not mention
1811                  * the use of DSA to sign ECParameters in the server
1812                  * key exchange message. We do support RSA and ECDSA.
1813                  */
1814                 if (0) ;
1815 #ifndef OPENSSL_NO_RSA
1816                 else if (alg_a & SSL_aRSA)
1817                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1818 #endif
1819 #ifndef OPENSSL_NO_ECDSA
1820                 else if (alg_a & SSL_aECDSA)
1821                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1822 #endif
1823                 /* else anonymous ECDH, so no certificate or pkey. */
1824                 EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1825                 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1826                 ecdh=NULL;
1827                 BN_CTX_free(bn_ctx);
1828                 bn_ctx = NULL;
1829                 EC_POINT_free(srvr_ecpoint);
1830                 srvr_ecpoint = NULL;
1831                 }
1832         else if (alg_k)
1833                 {
1834                 al=SSL_AD_UNEXPECTED_MESSAGE;
1835                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1836                 goto f_err;
1837                 }
1838 #endif /* !OPENSSL_NO_ECDH */
1839
1840
1841         /* p points to the next byte, there are 'n' bytes left */
1842
1843         /* if it was signed, check the signature */
1844         if (pkey != NULL)
1845                 {
1846                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
1847                         {
1848                         int sigalg;
1849                         if (2 > n)
1850                                 {
1851                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1852                                         SSL_R_LENGTH_TOO_SHORT);
1853                                 goto f_err;
1854                                 }
1855
1856                         sigalg = tls12_get_sigid(pkey);
1857                         /* Should never happen */
1858                         if (sigalg == -1)
1859                                 {
1860                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1861                                 goto err;
1862                                 }
1863                         /* Check key type is consistent with signature */
1864                         if (sigalg != (int)p[1])
1865                                 {
1866                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_TYPE);
1867                                 al=SSL_AD_DECODE_ERROR;
1868                                 goto f_err;
1869                                 }
1870                         md = tls12_get_hash(p[0]);
1871                         if (md == NULL)
1872                                 {
1873                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNKNOWN_DIGEST);
1874                                 goto f_err;
1875                                 }
1876 #ifdef SSL_DEBUG
1877 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
1878 #endif
1879                         p += 2;
1880                         n -= 2;
1881                         }
1882                 else
1883                         md = EVP_sha1();
1884
1885                 if (2 > n)
1886                         {
1887                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,
1888                                 SSL_R_LENGTH_TOO_SHORT);
1889                         goto f_err;
1890                         }
1891                 n2s(p,i);
1892                 n-=2;
1893                 j=EVP_PKEY_size(pkey);
1894
1895                 /* Check signature length. If n is 0 then signature is empty */
1896                 if ((i != n) || (n > j) || (n <= 0))
1897                         {
1898                         /* wrong packet length */
1899                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1900                         goto f_err;
1901                         }
1902
1903 #ifndef OPENSSL_NO_RSA
1904                 if (pkey->type == EVP_PKEY_RSA && TLS1_get_version(s) < TLS1_2_VERSION)
1905                         {
1906                         int num;
1907                         unsigned int size;
1908
1909                         j=0;
1910                         q=md_buf;
1911                         for (num=2; num > 0; num--)
1912                                 {
1913                                 EVP_MD_CTX_set_flags(&md_ctx,
1914                                         EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1915                                 EVP_DigestInit_ex(&md_ctx,(num == 2)
1916                                         ?s->ctx->md5:s->ctx->sha1, NULL);
1917                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1918                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1919                                 EVP_DigestUpdate(&md_ctx,param,param_len);
1920                                 EVP_DigestFinal_ex(&md_ctx,q,&size);
1921                                 q+=size;
1922                                 j+=size;
1923                                 }
1924                         i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
1925                                                                 pkey->pkey.rsa);
1926                         if (i < 0)
1927                                 {
1928                                 al=SSL_AD_DECRYPT_ERROR;
1929                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1930                                 goto f_err;
1931                                 }
1932                         if (i == 0)
1933                                 {
1934                                 /* bad signature */
1935                                 al=SSL_AD_DECRYPT_ERROR;
1936                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1937                                 goto f_err;
1938                                 }
1939                         }
1940                 else
1941 #endif
1942                         {
1943                         EVP_VerifyInit_ex(&md_ctx, md, NULL);
1944                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1945                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1946                         EVP_VerifyUpdate(&md_ctx,param,param_len);
1947                         if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 0)
1948                                 {
1949                                 /* bad signature */
1950                                 al=SSL_AD_DECRYPT_ERROR;
1951                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1952                                 goto f_err;
1953                                 }
1954                         }
1955                 }
1956         else
1957                 {
1958                 /* aNULL, aSRP or kPSK do not need public keys */
1959                 if (!(alg_a & (SSL_aNULL|SSL_aSRP)) && !(alg_k & SSL_kPSK))
1960                         {
1961                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1962                         goto err;
1963                         }
1964                 /* still data left over */
1965                 if (n != 0)
1966                         {
1967                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1968                         goto f_err;
1969                         }
1970                 }
1971         EVP_PKEY_free(pkey);
1972         EVP_MD_CTX_cleanup(&md_ctx);
1973         return(1);
1974 f_err:
1975         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1976 err:
1977         EVP_PKEY_free(pkey);
1978 #ifndef OPENSSL_NO_RSA
1979         if (rsa != NULL)
1980                 RSA_free(rsa);
1981 #endif
1982 #ifndef OPENSSL_NO_DH
1983         if (dh != NULL)
1984                 DH_free(dh);
1985 #endif
1986 #ifndef OPENSSL_NO_ECDH
1987         BN_CTX_free(bn_ctx);
1988         EC_POINT_free(srvr_ecpoint);
1989         if (ecdh != NULL)
1990                 EC_KEY_free(ecdh);
1991 #endif
1992         EVP_MD_CTX_cleanup(&md_ctx);
1993         return(-1);
1994         }
1995
1996 int ssl3_get_certificate_request(SSL *s)
1997         {
1998         int ok,ret=0;
1999         unsigned long n,nc,l;
2000         unsigned int llen, ctype_num,i;
2001         X509_NAME *xn=NULL;
2002         const unsigned char *p,*q;
2003         unsigned char *d;
2004         STACK_OF(X509_NAME) *ca_sk=NULL;
2005
2006         n=s->method->ssl_get_message(s,
2007                 SSL3_ST_CR_CERT_REQ_A,
2008                 SSL3_ST_CR_CERT_REQ_B,
2009                 -1,
2010                 s->max_cert_list,
2011                 &ok);
2012
2013         if (!ok) return((int)n);
2014
2015         s->s3->tmp.cert_req=0;
2016
2017         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
2018                 {
2019                 s->s3->tmp.reuse_message=1;
2020                 /* If we get here we don't need any cached handshake records
2021                  * as we wont be doing client auth.
2022                  */
2023                 if (s->s3->handshake_buffer)
2024                         {
2025                         if (!ssl3_digest_cached_records(s))
2026                                 goto err;
2027                         }
2028                 return(1);
2029                 }
2030
2031         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
2032                 {
2033                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2034                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
2035                 goto err;
2036                 }
2037
2038         /* TLS does not like anon-DH with client cert */
2039         if (s->version > SSL3_VERSION)
2040                 {
2041                 if (s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
2042                         {
2043                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2044                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
2045                         goto err;
2046                         }
2047                 }
2048
2049         p=d=(unsigned char *)s->init_msg;
2050
2051         if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
2052                 {
2053                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
2054                 goto err;
2055                 }
2056
2057         /* get the certificate types */
2058         ctype_num= *(p++);
2059         if (ctype_num > SSL3_CT_NUMBER)
2060                 ctype_num=SSL3_CT_NUMBER;
2061         for (i=0; i<ctype_num; i++)
2062                 s->s3->tmp.ctype[i]= p[i];
2063         p+=ctype_num;
2064         if (TLS1_get_version(s) >= TLS1_2_VERSION)
2065                 {
2066                 n2s(p, llen);
2067                 /* Check we have enough room for signature algorithms and
2068                  * following length value.
2069                  */
2070                 if ((unsigned long)(p - d + llen + 2) > n)
2071                         {
2072                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2073                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_DATA_LENGTH_TOO_LONG);
2074                         goto err;
2075                         }
2076                 if ((llen & 1) || !tls1_process_sigalgs(s, p, llen))
2077                         {
2078                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2079                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_SIGNATURE_ALGORITHMS_ERROR);
2080                         goto err;
2081                         }
2082                 p += llen;
2083                 }
2084
2085         /* get the CA RDNs */
2086         n2s(p,llen);
2087 #if 0
2088 {
2089 FILE *out;
2090 out=fopen("/tmp/vsign.der","w");
2091 fwrite(p,1,llen,out);
2092 fclose(out);
2093 }
2094 #endif
2095
2096         if ((unsigned long)(p - d + llen) != n)
2097                 {
2098                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2099                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
2100                 goto err;
2101                 }
2102
2103         for (nc=0; nc<llen; )
2104                 {
2105                 n2s(p,l);
2106                 if ((l+nc+2) > llen)
2107                         {
2108                         if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2109                                 goto cont; /* netscape bugs */
2110                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2111                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
2112                         goto err;
2113                         }
2114
2115                 q=p;
2116
2117                 if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
2118                         {
2119                         /* If netscape tolerance is on, ignore errors */
2120                         if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
2121                                 goto cont;
2122                         else
2123                                 {
2124                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2125                                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
2126                                 goto err;
2127                                 }
2128                         }
2129
2130                 if (q != (p+l))
2131                         {
2132                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2133                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
2134                         goto err;
2135                         }
2136                 if (!sk_X509_NAME_push(ca_sk,xn))
2137                         {
2138                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
2139                         goto err;
2140                         }
2141
2142                 p+=l;
2143                 nc+=l+2;
2144                 }
2145
2146         if (0)
2147                 {
2148 cont:
2149                 ERR_clear_error();
2150                 }
2151
2152         /* we should setup a certificate to return.... */
2153         s->s3->tmp.cert_req=1;
2154         s->s3->tmp.ctype_num=ctype_num;
2155         if (s->s3->tmp.ca_names != NULL)
2156                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
2157         s->s3->tmp.ca_names=ca_sk;
2158         ca_sk=NULL;
2159
2160         ret=1;
2161 err:
2162         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
2163         return(ret);
2164         }
2165
2166 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
2167         {
2168         return(X509_NAME_cmp(*a,*b));
2169         }
2170 #ifndef OPENSSL_NO_TLSEXT
2171 int ssl3_get_new_session_ticket(SSL *s)
2172         {
2173         int ok,al,ret=0, ticklen;
2174         long n;
2175         const unsigned char *p;
2176         unsigned char *d;
2177
2178         n=s->method->ssl_get_message(s,
2179                 SSL3_ST_CR_SESSION_TICKET_A,
2180                 SSL3_ST_CR_SESSION_TICKET_B,
2181                 -1,
2182                 16384,
2183                 &ok);
2184
2185         if (!ok)
2186                 return((int)n);
2187
2188         if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
2189                 {
2190                 s->s3->tmp.reuse_message=1;
2191                 return(1);
2192                 }
2193         if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
2194                 {
2195                 al=SSL_AD_UNEXPECTED_MESSAGE;
2196                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
2197                 goto f_err;
2198                 }
2199         if (n < 6)
2200                 {
2201                 /* need at least ticket_lifetime_hint + ticket length */
2202                 al = SSL_AD_DECODE_ERROR;
2203                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2204                 goto f_err;
2205                 }
2206
2207         p=d=(unsigned char *)s->init_msg;
2208         n2l(p, s->session->tlsext_tick_lifetime_hint);
2209         n2s(p, ticklen);
2210         /* ticket_lifetime_hint + ticket_length + ticket */
2211         if (ticklen + 6 != n)
2212                 {
2213                 al = SSL_AD_DECODE_ERROR;
2214                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
2215                 goto f_err;
2216                 }
2217         if (s->session->tlsext_tick)
2218                 {
2219                 OPENSSL_free(s->session->tlsext_tick);
2220                 s->session->tlsext_ticklen = 0;
2221                 }
2222         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
2223         if (!s->session->tlsext_tick)
2224                 {
2225                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
2226                 goto err;
2227                 }
2228         memcpy(s->session->tlsext_tick, p, ticklen);
2229         s->session->tlsext_ticklen = ticklen;
2230         /* There are two ways to detect a resumed ticket session.
2231          * One is to set an appropriate session ID and then the server
2232          * must return a match in ServerHello. This allows the normal
2233          * client session ID matching to work and we know much 
2234          * earlier that the ticket has been accepted.
2235          * 
2236          * The other way is to set zero length session ID when the
2237          * ticket is presented and rely on the handshake to determine
2238          * session resumption.
2239          *
2240          * We choose the former approach because this fits in with
2241          * assumptions elsewhere in OpenSSL. The session ID is set
2242          * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
2243          * ticket.
2244          */ 
2245         EVP_Digest(p, ticklen,
2246                         s->session->session_id, &s->session->session_id_length,
2247 #ifndef OPENSSL_NO_SHA256
2248                                                         EVP_sha256(), NULL);
2249 #else
2250                                                         EVP_sha1(), NULL);
2251 #endif
2252         ret=1;
2253         return(ret);
2254 f_err:
2255         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2256 err:
2257         return(-1);
2258         }
2259
2260 int ssl3_get_cert_status(SSL *s)
2261         {
2262         int ok, al;
2263         unsigned long resplen,n;
2264         const unsigned char *p;
2265
2266         n=s->method->ssl_get_message(s,
2267                 SSL3_ST_CR_CERT_STATUS_A,
2268                 SSL3_ST_CR_CERT_STATUS_B,
2269                 SSL3_MT_CERTIFICATE_STATUS,
2270                 16384,
2271                 &ok);
2272
2273         if (!ok) return((int)n);
2274         if (n < 4)
2275                 {
2276                 /* need at least status type + length */
2277                 al = SSL_AD_DECODE_ERROR;
2278                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2279                 goto f_err;
2280                 }
2281         p = (unsigned char *)s->init_msg;
2282         if (*p++ != TLSEXT_STATUSTYPE_ocsp)
2283                 {
2284                 al = SSL_AD_DECODE_ERROR;
2285                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
2286                 goto f_err;
2287                 }
2288         n2l3(p, resplen);
2289         if (resplen + 4 != n)
2290                 {
2291                 al = SSL_AD_DECODE_ERROR;
2292                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
2293                 goto f_err;
2294                 }
2295         if (s->tlsext_ocsp_resp)
2296                 OPENSSL_free(s->tlsext_ocsp_resp);
2297         s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
2298         if (!s->tlsext_ocsp_resp)
2299                 {
2300                 al = SSL_AD_INTERNAL_ERROR;
2301                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2302                 goto f_err;
2303                 }
2304         s->tlsext_ocsp_resplen = resplen;
2305         if (s->ctx->tlsext_status_cb)
2306                 {
2307                 int ret;
2308                 ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
2309                 if (ret == 0)
2310                         {
2311                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
2312                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
2313                         goto f_err;
2314                         }
2315                 if (ret < 0)
2316                         {
2317                         al = SSL_AD_INTERNAL_ERROR;
2318                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
2319                         goto f_err;
2320                         }
2321                 }
2322         return 1;
2323 f_err:
2324         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2325         return(-1);
2326         }
2327 #endif
2328
2329 int ssl3_get_server_done(SSL *s)
2330         {
2331         int ok,ret=0;
2332         long n;
2333
2334         n=s->method->ssl_get_message(s,
2335                 SSL3_ST_CR_SRVR_DONE_A,
2336                 SSL3_ST_CR_SRVR_DONE_B,
2337                 SSL3_MT_SERVER_DONE,
2338                 30, /* should be very small, like 0 :-) */
2339                 &ok);
2340
2341         if (!ok) return((int)n);
2342         if (n > 0)
2343                 {
2344                 /* should contain no data */
2345                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
2346                 SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
2347                 return -1;
2348                 }
2349         ret=1;
2350         return(ret);
2351         }
2352
2353
2354 int ssl3_send_client_key_exchange(SSL *s)
2355         {
2356         unsigned char *p,*d;
2357         int n;
2358         unsigned long alg_k;
2359 #ifndef OPENSSL_NO_RSA
2360         unsigned char *q;
2361         EVP_PKEY *pkey=NULL;
2362 #endif
2363 #ifndef OPENSSL_NO_KRB5
2364         KSSL_ERR kssl_err;
2365 #endif /* OPENSSL_NO_KRB5 */
2366 #ifndef OPENSSL_NO_ECDH
2367         EC_KEY *clnt_ecdh = NULL;
2368         const EC_POINT *srvr_ecpoint = NULL;
2369         EVP_PKEY *srvr_pub_pkey = NULL;
2370         unsigned char *encodedPoint = NULL;
2371         int encoded_pt_len = 0;
2372         BN_CTX * bn_ctx = NULL;
2373 #endif
2374
2375         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
2376                 {
2377                 d=(unsigned char *)s->init_buf->data;
2378                 p= &(d[4]);
2379
2380                 alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2381
2382                 /* Fool emacs indentation */
2383                 if (0) {}
2384 #ifndef OPENSSL_NO_RSA
2385                 else if (alg_k & SSL_kRSA)
2386                         {
2387                         RSA *rsa;
2388                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2389
2390                         if (s->session->sess_cert == NULL)
2391                                 {
2392                                 /* We should always have a server certificate with SSL_kRSA. */
2393                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2394                                 goto err;
2395                                 }
2396
2397                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
2398                                 rsa=s->session->sess_cert->peer_rsa_tmp;
2399                         else
2400                                 {
2401                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
2402                                 if ((pkey == NULL) ||
2403                                         (pkey->type != EVP_PKEY_RSA) ||
2404                                         (pkey->pkey.rsa == NULL))
2405                                         {
2406                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2407                                         goto err;
2408                                         }
2409                                 rsa=pkey->pkey.rsa;
2410                                 EVP_PKEY_free(pkey);
2411                                 }
2412                                 
2413                         tmp_buf[0]=s->client_version>>8;
2414                         tmp_buf[1]=s->client_version&0xff;
2415                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2416                                         goto err;
2417
2418                         s->session->master_key_length=sizeof tmp_buf;
2419
2420                         q=p;
2421                         /* Fix buf for TLS and beyond */
2422                         if (s->version > SSL3_VERSION)
2423                                 p+=2;
2424                         n=RSA_public_encrypt(sizeof tmp_buf,
2425                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
2426 #ifdef PKCS1_CHECK
2427                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
2428                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
2429 #endif
2430                         if (n <= 0)
2431                                 {
2432                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
2433                                 goto err;
2434                                 }
2435
2436                         /* Fix buf for TLS and beyond */
2437                         if (s->version > SSL3_VERSION)
2438                                 {
2439                                 s2n(n,q);
2440                                 n+=2;
2441                                 }
2442
2443                         s->session->master_key_length=
2444                                 s->method->ssl3_enc->generate_master_secret(s,
2445                                         s->session->master_key,
2446                                         tmp_buf,sizeof tmp_buf);
2447                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
2448                         }
2449 #endif
2450 #ifndef OPENSSL_NO_KRB5
2451                 else if (alg_k & SSL_kKRB5)
2452                         {
2453                         krb5_error_code krb5rc;
2454                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
2455                         /*  krb5_data   krb5_ap_req;  */
2456                         krb5_data       *enc_ticket;
2457                         krb5_data       authenticator, *authp = NULL;
2458                         EVP_CIPHER_CTX  ciph_ctx;
2459                         const EVP_CIPHER *enc = NULL;
2460                         unsigned char   iv[EVP_MAX_IV_LENGTH];
2461                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
2462                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
2463                                                 + EVP_MAX_IV_LENGTH];
2464                         int             padl, outl = sizeof(epms);
2465
2466                         EVP_CIPHER_CTX_init(&ciph_ctx);
2467
2468 #ifdef KSSL_DEBUG
2469                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
2470                                 alg_k, SSL_kKRB5);
2471 #endif  /* KSSL_DEBUG */
2472
2473                         authp = NULL;
2474 #ifdef KRB5SENDAUTH
2475                         if (KRB5SENDAUTH)  authp = &authenticator;
2476 #endif  /* KRB5SENDAUTH */
2477
2478                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
2479                                 &kssl_err);
2480                         enc = kssl_map_enc(kssl_ctx->enctype);
2481                         if (enc == NULL)
2482                             goto err;
2483 #ifdef KSSL_DEBUG
2484                         {
2485                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
2486                         if (krb5rc && kssl_err.text)
2487                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
2488                         }
2489 #endif  /* KSSL_DEBUG */
2490
2491                         if (krb5rc)
2492                                 {
2493                                 ssl3_send_alert(s,SSL3_AL_FATAL,
2494                                                 SSL_AD_HANDSHAKE_FAILURE);
2495                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2496                                                 kssl_err.reason);
2497                                 goto err;
2498                                 }
2499
2500                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
2501                         **  in place of RFC 2712 KerberosWrapper, as in:
2502                         **
2503                         **  Send ticket (copy to *p, set n = length)
2504                         **  n = krb5_ap_req.length;
2505                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2506                         **  if (krb5_ap_req.data)  
2507                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2508                         **
2509                         **  Now using real RFC 2712 KerberosWrapper
2510                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2511                         **  Note: 2712 "opaque" types are here replaced
2512                         **  with a 2-byte length followed by the value.
2513                         **  Example:
2514                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2515                         **  Where "xx xx" = length bytes.  Shown here with
2516                         **  optional authenticator omitted.
2517                         */
2518
2519                         /*  KerberosWrapper.Ticket              */
2520                         s2n(enc_ticket->length,p);
2521                         memcpy(p, enc_ticket->data, enc_ticket->length);
2522                         p+= enc_ticket->length;
2523                         n = enc_ticket->length + 2;
2524
2525                         /*  KerberosWrapper.Authenticator       */
2526                         if (authp  &&  authp->length)  
2527                                 {
2528                                 s2n(authp->length,p);
2529                                 memcpy(p, authp->data, authp->length);
2530                                 p+= authp->length;
2531                                 n+= authp->length + 2;
2532                                 
2533                                 free(authp->data);
2534                                 authp->data = NULL;
2535                                 authp->length = 0;
2536                                 }
2537                         else
2538                                 {
2539                                 s2n(0,p);/*  null authenticator length  */
2540                                 n+=2;
2541                                 }
2542  
2543                             tmp_buf[0]=s->client_version>>8;
2544                             tmp_buf[1]=s->client_version&0xff;
2545                             if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2546                                 goto err;
2547
2548                         /*  20010420 VRS.  Tried it this way; failed.
2549                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2550                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2551                         **                              kssl_ctx->length);
2552                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2553                         */
2554
2555                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
2556                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
2557                                 kssl_ctx->key,iv);
2558                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
2559                                 sizeof tmp_buf);
2560                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
2561                         outl += padl;
2562                         if (outl > (int)sizeof epms)
2563                                 {
2564                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2565                                 goto err;
2566                                 }
2567                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2568
2569                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
2570                         s2n(outl,p);
2571                         memcpy(p, epms, outl);
2572                         p+=outl;
2573                         n+=outl + 2;
2574
2575                         s->session->master_key_length=
2576                                 s->method->ssl3_enc->generate_master_secret(s,
2577                                         s->session->master_key,
2578                                         tmp_buf, sizeof tmp_buf);
2579
2580                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2581                         OPENSSL_cleanse(epms, outl);
2582                         }
2583 #endif
2584 #ifndef OPENSSL_NO_DH
2585                 else if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2586                         {
2587                         DH *dh_srvr,*dh_clnt;
2588
2589                         if (s->session->sess_cert == NULL) 
2590                                 {
2591                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2592                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2593                                 goto err;
2594                                 }
2595
2596                         if (s->session->sess_cert->peer_dh_tmp != NULL)
2597                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
2598                         else
2599                                 {
2600                                 /* we get them from the cert */
2601                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2602                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2603                                 goto err;
2604                                 }
2605                         
2606                         /* generate a new random key */
2607                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2608                                 {
2609                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2610                                 goto err;
2611                                 }
2612                         if (!DH_generate_key(dh_clnt))
2613                                 {
2614                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2615                                 DH_free(dh_clnt);
2616                                 goto err;
2617                                 }
2618
2619                         /* use the 'p' output buffer for the DH key, but
2620                          * make sure to clear it out afterwards */
2621
2622                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
2623
2624                         if (n <= 0)
2625                                 {
2626                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2627                                 DH_free(dh_clnt);
2628                                 goto err;
2629                                 }
2630
2631                         /* generate master key from the result */
2632                         s->session->master_key_length=
2633                                 s->method->ssl3_enc->generate_master_secret(s,
2634                                         s->session->master_key,p,n);
2635                         /* clean up */
2636                         memset(p,0,n);
2637
2638                         /* send off the data */
2639                         n=BN_num_bytes(dh_clnt->pub_key);
2640                         s2n(n,p);
2641                         BN_bn2bin(dh_clnt->pub_key,p);
2642                         n+=2;
2643
2644                         DH_free(dh_clnt);
2645
2646                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
2647                         }
2648 #endif
2649
2650 #ifndef OPENSSL_NO_ECDH 
2651                 else if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2652                         {
2653                         const EC_GROUP *srvr_group = NULL;
2654                         EC_KEY *tkey;
2655                         int ecdh_clnt_cert = 0;
2656                         int field_size = 0;
2657
2658                         if (s->session->sess_cert == NULL) 
2659                                 {
2660                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2661                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2662                                 goto err;
2663                                 }
2664
2665                         /* Did we send out the client's
2666                          * ECDH share for use in premaster
2667                          * computation as part of client certificate?
2668                          * If so, set ecdh_clnt_cert to 1.
2669                          */
2670                         if ((alg_k & (SSL_kECDHr|SSL_kECDHe)) && (s->cert != NULL)) 
2671                                 {
2672                                 /* XXX: For now, we do not support client
2673                                  * authentication using ECDH certificates.
2674                                  * To add such support, one needs to add
2675                                  * code that checks for appropriate 
2676                                  * conditions and sets ecdh_clnt_cert to 1.
2677                                  * For example, the cert have an ECC
2678                                  * key on the same curve as the server's
2679                                  * and the key should be authorized for
2680                                  * key agreement.
2681                                  *
2682                                  * One also needs to add code in ssl3_connect
2683                                  * to skip sending the certificate verify
2684                                  * message.
2685                                  *
2686                                  * if ((s->cert->key->privatekey != NULL) &&
2687                                  *     (s->cert->key->privatekey->type ==
2688                                  *      EVP_PKEY_EC) && ...)
2689                                  * ecdh_clnt_cert = 1;
2690                                  */
2691                                 }
2692
2693                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
2694                                 {
2695                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
2696                                 }
2697                         else
2698                                 {
2699                                 /* Get the Server Public Key from Cert */
2700                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
2701                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2702                                 if ((srvr_pub_pkey == NULL) ||
2703                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
2704                                     (srvr_pub_pkey->pkey.ec == NULL))
2705                                         {
2706                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2707                                             ERR_R_INTERNAL_ERROR);
2708                                         goto err;
2709                                         }
2710
2711                                 tkey = srvr_pub_pkey->pkey.ec;
2712                                 }
2713
2714                         srvr_group   = EC_KEY_get0_group(tkey);
2715                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2716
2717                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2718                                 {
2719                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2720                                     ERR_R_INTERNAL_ERROR);
2721                                 goto err;
2722                                 }
2723
2724                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
2725                                 {
2726                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2727                                 goto err;
2728                                 }
2729
2730                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2731                                 {
2732                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2733                                 goto err;
2734                                 }
2735                         if (ecdh_clnt_cert) 
2736                                 { 
2737                                 /* Reuse key info from our certificate
2738                                  * We only need our private key to perform
2739                                  * the ECDH computation.
2740                                  */
2741                                 const BIGNUM *priv_key;
2742                                 tkey = s->cert->key->privatekey->pkey.ec;
2743                                 priv_key = EC_KEY_get0_private_key(tkey);
2744                                 if (priv_key == NULL)
2745                                         {
2746                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2747                                         goto err;
2748                                         }
2749                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
2750                                         {
2751                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2752                                         goto err;
2753                                         }
2754                                 }
2755                         else 
2756                                 {
2757                                 /* Generate a new ECDH key pair */
2758                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
2759                                         {
2760                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2761                                         goto err;
2762                                         }
2763                                 }
2764
2765                         /* use the 'p' output buffer for the ECDH key, but
2766                          * make sure to clear it out afterwards
2767                          */
2768
2769                         field_size = EC_GROUP_get_degree(srvr_group);
2770                         if (field_size <= 0)
2771                                 {
2772                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2773                                        ERR_R_ECDH_LIB);
2774                                 goto err;
2775                                 }
2776                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
2777                         if (n <= 0)
2778                                 {
2779                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2780                                        ERR_R_ECDH_LIB);
2781                                 goto err;
2782                                 }
2783
2784                         /* generate master key from the result */
2785                         s->session->master_key_length = s->method->ssl3_enc \
2786                             -> generate_master_secret(s, 
2787                                 s->session->master_key,
2788                                 p, n);
2789
2790                         memset(p, 0, n); /* clean up */
2791
2792                         if (ecdh_clnt_cert) 
2793                                 {
2794                                 /* Send empty client key exch message */
2795                                 n = 0;
2796                                 }
2797                         else 
2798                                 {
2799                                 /* First check the size of encoding and
2800                                  * allocate memory accordingly.
2801                                  */
2802                                 encoded_pt_len = 
2803                                     EC_POINT_point2oct(srvr_group, 
2804                                         EC_KEY_get0_public_key(clnt_ecdh), 
2805                                         POINT_CONVERSION_UNCOMPRESSED, 
2806                                         NULL, 0, NULL);
2807
2808                                 encodedPoint = (unsigned char *) 
2809                                     OPENSSL_malloc(encoded_pt_len * 
2810                                         sizeof(unsigned char)); 
2811                                 bn_ctx = BN_CTX_new();
2812                                 if ((encodedPoint == NULL) || 
2813                                     (bn_ctx == NULL)) 
2814                                         {
2815                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2816                                         goto err;
2817                                         }
2818
2819                                 /* Encode the public key */
2820                                 n = EC_POINT_point2oct(srvr_group, 
2821                                     EC_KEY_get0_public_key(clnt_ecdh), 
2822                                     POINT_CONVERSION_UNCOMPRESSED, 
2823                                     encodedPoint, encoded_pt_len, bn_ctx);
2824
2825                                 *p = n; /* length of encoded point */
2826                                 /* Encoded point will be copied here */
2827                                 p += 1; 
2828                                 /* copy the point */
2829                                 memcpy((unsigned char *)p, encodedPoint, n);
2830                                 /* increment n to account for length field */
2831                                 n += 1; 
2832                                 }
2833
2834                         /* Free allocated memory */
2835                         BN_CTX_free(bn_ctx);
2836                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2837                         if (clnt_ecdh != NULL) 
2838                                  EC_KEY_free(clnt_ecdh);
2839                         EVP_PKEY_free(srvr_pub_pkey);
2840                         }
2841 #endif /* !OPENSSL_NO_ECDH */
2842                 else if (alg_k & SSL_kGOST) 
2843                         {
2844                         /* GOST key exchange message creation */
2845                         EVP_PKEY_CTX *pkey_ctx;
2846                         X509 *peer_cert; 
2847                         size_t msglen;
2848                         unsigned int md_len;
2849                         int keytype;
2850                         unsigned char premaster_secret[32],shared_ukm[32], tmp[256];
2851                         EVP_MD_CTX *ukm_hash;
2852                         EVP_PKEY *pub_key;
2853
2854                         /* Get server sertificate PKEY and create ctx from it */
2855                         peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST01)].x509;
2856                         if (!peer_cert) 
2857                                 peer_cert=s->session->sess_cert->peer_pkeys[(keytype=SSL_PKEY_GOST94)].x509;
2858                         if (!peer_cert)         {
2859                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_NO_GOST_CERTIFICATE_SENT_BY_PEER);
2860                                         goto err;
2861                                 }       
2862                                 
2863                         pkey_ctx=EVP_PKEY_CTX_new(pub_key=X509_get_pubkey(peer_cert),NULL);
2864                         /* If we have send a certificate, and certificate key
2865
2866                          * parameters match those of server certificate, use
2867                          * certificate key for key exchange
2868                          */
2869
2870                          /* Otherwise, generate ephemeral key pair */
2871                                         
2872                         EVP_PKEY_encrypt_init(pkey_ctx);
2873                           /* Generate session key */    
2874                     RAND_bytes(premaster_secret,32);
2875                         /* If we have client certificate, use its secret as peer key */
2876                         if (s->s3->tmp.cert_req && s->cert->key->privatekey) {
2877                                 if (EVP_PKEY_derive_set_peer(pkey_ctx,s->cert->key->privatekey) <=0) {
2878                                         /* If there was an error - just ignore it. Ephemeral key
2879                                         * would be used
2880                                         */
2881                                         ERR_clear_error();
2882                                 }
2883                         }                       
2884                         /* Compute shared IV and store it in algorithm-specific
2885                          * context data */
2886                         ukm_hash = EVP_MD_CTX_create();
2887                         EVP_DigestInit(ukm_hash,EVP_get_digestbynid(NID_id_GostR3411_94));
2888                         EVP_DigestUpdate(ukm_hash,s->s3->client_random,SSL3_RANDOM_SIZE);
2889                         EVP_DigestUpdate(ukm_hash,s->s3->server_random,SSL3_RANDOM_SIZE);
2890                         EVP_DigestFinal_ex(ukm_hash, shared_ukm, &md_len);
2891                         EVP_MD_CTX_destroy(ukm_hash);
2892                         if (EVP_PKEY_CTX_ctrl(pkey_ctx,-1,EVP_PKEY_OP_ENCRYPT,EVP_PKEY_CTRL_SET_IV,
2893                                 8,shared_ukm)<0) {
2894                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2895                                                 SSL_R_LIBRARY_BUG);
2896                                         goto err;
2897                                 }       
2898                         /* Make GOST keytransport blob message */
2899                         /*Encapsulate it into sequence */
2900                         *(p++)=V_ASN1_SEQUENCE | V_ASN1_CONSTRUCTED;
2901                         msglen=255;
2902                         if (EVP_PKEY_encrypt(pkey_ctx,tmp,&msglen,premaster_secret,32)<0) {
2903                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2904                                         SSL_R_LIBRARY_BUG);
2905                                 goto err;
2906                         }
2907                         if (msglen >= 0x80)
2908                                 {
2909                                 *(p++)=0x81;
2910                                 *(p++)= msglen & 0xff;
2911                                 n=msglen+3;
2912                                 }
2913                         else
2914                                 {
2915                                 *(p++)= msglen & 0xff;
2916                                 n=msglen+2;
2917                                 }
2918                         memcpy(p, tmp, msglen);
2919                         /* Check if pubkey from client certificate was used */
2920                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2921                                 {
2922                                 /* Set flag "skip certificate verify" */
2923                                 s->s3->flags |= TLS1_FLAGS_SKIP_CERT_VERIFY;
2924                                 }
2925                         EVP_PKEY_CTX_free(pkey_ctx);
2926                         s->session->master_key_length=
2927                                 s->method->ssl3_enc->generate_master_secret(s,
2928                                         s->session->master_key,premaster_secret,32);
2929                         EVP_PKEY_free(pub_key);
2930
2931                         }
2932 #ifndef OPENSSL_NO_SRP
2933                 else if (alg_k & SSL_kSRP)
2934                         {
2935                         if (s->srp_ctx.A != NULL)
2936                                 {
2937                                 /* send off the data */
2938                                 n=BN_num_bytes(s->srp_ctx.A);
2939                                 s2n(n,p);
2940                                 BN_bn2bin(s->srp_ctx.A,p);
2941                                 n+=2;
2942                                 }
2943                         else
2944                                 {
2945                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2946                                 goto err;
2947                                 }
2948                         if (s->session->srp_username != NULL)
2949                                 OPENSSL_free(s->session->srp_username);
2950                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2951                         if (s->session->srp_username == NULL)
2952                                 {
2953                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2954                                         ERR_R_MALLOC_FAILURE);
2955                                 goto err;
2956                                 }
2957
2958                         if ((s->session->master_key_length = SRP_generate_client_master_secret(s,s->session->master_key))<0)
2959                                 {
2960                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2961                                 goto err;
2962                                 }
2963                         }
2964 #endif
2965 #ifndef OPENSSL_NO_PSK
2966                 else if (alg_k & SSL_kPSK)
2967                         {
2968                         /* The callback needs PSK_MAX_IDENTITY_LEN + 1 bytes
2969                          * to return a \0-terminated identity. The last byte
2970                          * is for us for simulating strnlen. */
2971                         char identity[PSK_MAX_IDENTITY_LEN + 2];
2972                         size_t identity_len;
2973                         unsigned char *t = NULL;
2974                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2975                         unsigned int pre_ms_len = 0, psk_len = 0;
2976                         int psk_err = 1;
2977
2978                         n = 0;
2979                         if (s->psk_client_callback == NULL)
2980                                 {
2981                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2982                                         SSL_R_PSK_NO_CLIENT_CB);
2983                                 goto err;
2984                                 }
2985
2986                         memset(identity, 0, sizeof(identity));
2987                         psk_len = s->psk_client_callback(s, s->ctx->psk_identity_hint,
2988                                 identity, sizeof(identity) - 1,
2989                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2990                         if (psk_len > PSK_MAX_PSK_LEN)
2991                                 {
2992                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2993                                         ERR_R_INTERNAL_ERROR);
2994                                 goto psk_err;
2995                                 }
2996                         else if (psk_len == 0)
2997                                 {
2998                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2999                                         SSL_R_PSK_IDENTITY_NOT_FOUND);
3000                                 goto psk_err;
3001                                 }
3002                         identity[PSK_MAX_IDENTITY_LEN + 1] = '\0';
3003                         identity_len = strlen(identity);
3004                         if (identity_len > PSK_MAX_IDENTITY_LEN)
3005                                 {
3006                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3007                                         ERR_R_INTERNAL_ERROR);
3008                                 goto psk_err;
3009                                 }
3010                         /* create PSK pre_master_secret */
3011                         pre_ms_len = 2+psk_len+2+psk_len;
3012                         t = psk_or_pre_ms;
3013                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
3014                         s2n(psk_len, t);
3015                         memset(t, 0, psk_len);
3016                         t+=psk_len;
3017                         s2n(psk_len, t);
3018
3019                         if (s->session->psk_identity_hint != NULL)
3020                                 OPENSSL_free(s->session->psk_identity_hint);
3021                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
3022                         if (s->ctx->psk_identity_hint != NULL &&
3023                                 s->session->psk_identity_hint == NULL)
3024                                 {
3025                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3026                                         ERR_R_MALLOC_FAILURE);
3027                                 goto psk_err;
3028                                 }
3029
3030                         if (s->session->psk_identity != NULL)
3031                                 OPENSSL_free(s->session->psk_identity);
3032                         s->session->psk_identity = BUF_strdup(identity);
3033                         if (s->session->psk_identity == NULL)
3034                                 {
3035                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3036                                         ERR_R_MALLOC_FAILURE);
3037                                 goto psk_err;
3038                                 }
3039
3040                         s->session->master_key_length =
3041                                 s->method->ssl3_enc->generate_master_secret(s,
3042                                         s->session->master_key,
3043                                         psk_or_pre_ms, pre_ms_len);
3044                         s2n(identity_len, p);
3045                         memcpy(p, identity, identity_len);
3046                         n = 2 + identity_len;
3047                         psk_err = 0;
3048                 psk_err:
3049                         OPENSSL_cleanse(identity, sizeof(identity));
3050                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
3051                         if (psk_err != 0)
3052                                 {
3053                                 ssl3_send_alert(s, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
3054                                 goto err;
3055                                 }
3056                         }
3057 #endif
3058                 else
3059                         {
3060                         ssl3_send_alert(s, SSL3_AL_FATAL,
3061                             SSL_AD_HANDSHAKE_FAILURE);
3062                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
3063                             ERR_R_INTERNAL_ERROR);
3064                         goto err;
3065                         }
3066                 
3067                 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
3068                 l2n3(n,d);
3069
3070                 s->state=SSL3_ST_CW_KEY_EXCH_B;
3071                 /* number of bytes to write */
3072                 s->init_num=n+4;
3073                 s->init_off=0;
3074                 }
3075
3076         /* SSL3_ST_CW_KEY_EXCH_B */
3077         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3078 err:
3079 #ifndef OPENSSL_NO_ECDH
3080         BN_CTX_free(bn_ctx);
3081         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
3082         if (clnt_ecdh != NULL) 
3083                 EC_KEY_free(clnt_ecdh);
3084         EVP_PKEY_free(srvr_pub_pkey);
3085 #endif
3086         return(-1);
3087         }
3088
3089 int ssl3_send_client_verify(SSL *s)
3090         {
3091         unsigned char *p,*d;
3092         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
3093         EVP_PKEY *pkey;
3094         EVP_PKEY_CTX *pctx=NULL;
3095         EVP_MD_CTX mctx;
3096         unsigned u=0;
3097         unsigned long n;
3098         int j;
3099
3100         EVP_MD_CTX_init(&mctx);
3101
3102         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
3103                 {
3104                 d=(unsigned char *)s->init_buf->data;
3105                 p= &(d[4]);
3106                 pkey=s->cert->key->privatekey;
3107 /* Create context from key and test if sha1 is allowed as digest */
3108                 pctx = EVP_PKEY_CTX_new(pkey,NULL);
3109                 EVP_PKEY_sign_init(pctx);
3110                 if (EVP_PKEY_CTX_set_signature_md(pctx, EVP_sha1())>0)
3111                         {