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