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