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