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