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