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