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