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