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