Fix for CVE-2014-0224
[openssl.git] / ssl / s3_clnt.c
1 /* ssl/s3_clnt.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2003 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111 /* ====================================================================
112  * Copyright 2002 Sun Microsystems, Inc. ALL RIGHTS RESERVED.
113  *
114  * Portions of the attached software ("Contribution") are developed by 
115  * SUN MICROSYSTEMS, INC., and are contributed to the OpenSSL project.
116  *
117  * The Contribution is licensed pursuant to the OpenSSL open source
118  * license provided above.
119  *
120  * ECC cipher suite support in OpenSSL originally written by
121  * Vipul Gupta and Sumit Gupta of Sun Microsystems Laboratories.
122  *
123  */
124
125 #include <stdio.h>
126 #include "ssl_locl.h"
127 #include "kssl_lcl.h"
128 #include <openssl/buffer.h>
129 #include <openssl/rand.h>
130 #include <openssl/objects.h>
131 #include <openssl/evp.h>
132 #include <openssl/md5.h>
133 #ifdef OPENSSL_FIPS
134 #include <openssl/fips.h>
135 #endif
136
137 #ifndef OPENSSL_NO_DH
138 #include <openssl/dh.h>
139 #endif
140 #include <openssl/bn.h>
141 #ifndef OPENSSL_NO_ENGINE
142 #include <openssl/engine.h>
143 #endif
144
145 static SSL_METHOD *ssl3_get_client_method(int ver);
146 static int ca_dn_cmp(const X509_NAME * const *a,const X509_NAME * const *b);
147
148 #ifndef OPENSSL_NO_ECDH
149 static int curve_id2nid(int curve_id);
150 int check_srvr_ecc_cert_and_alg(X509 *x, SSL_CIPHER *cs);
151 #endif
152
153 static SSL_METHOD *ssl3_get_client_method(int ver)
154         {
155         if (ver == SSL3_VERSION)
156                 return(SSLv3_client_method());
157         else
158                 return(NULL);
159         }
160
161 IMPLEMENT_ssl3_meth_func(SSLv3_client_method,
162                         ssl_undefined_function,
163                         ssl3_connect,
164                         ssl3_get_client_method)
165
166 int ssl3_connect(SSL *s)
167         {
168         BUF_MEM *buf=NULL;
169         unsigned long Time=(unsigned long)time(NULL);
170         void (*cb)(const SSL *ssl,int type,int val)=NULL;
171         int ret= -1;
172         int new_state,state,skip=0;
173
174         RAND_add(&Time,sizeof(Time),0);
175         ERR_clear_error();
176         clear_sys_error();
177
178         if (s->info_callback != NULL)
179                 cb=s->info_callback;
180         else if (s->ctx->info_callback != NULL)
181                 cb=s->ctx->info_callback;
182         
183         s->in_handshake++;
184         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s); 
185
186         for (;;)
187                 {
188                 state=s->state;
189
190                 switch(s->state)
191                         {
192                 case SSL_ST_RENEGOTIATE:
193                         s->new_session=1;
194                         s->state=SSL_ST_CONNECT;
195                         s->ctx->stats.sess_connect_renegotiate++;
196                         /* break */
197                 case SSL_ST_BEFORE:
198                 case SSL_ST_CONNECT:
199                 case SSL_ST_BEFORE|SSL_ST_CONNECT:
200                 case SSL_ST_OK|SSL_ST_CONNECT:
201
202                         s->server=0;
203                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
204
205                         if ((s->version & 0xff00 ) != 0x0300)
206                                 {
207                                 SSLerr(SSL_F_SSL3_CONNECT, ERR_R_INTERNAL_ERROR);
208                                 ret = -1;
209                                 goto end;
210                                 }
211                                 
212                         /* s->version=SSL3_VERSION; */
213                         s->type=SSL_ST_CONNECT;
214
215                         if (s->init_buf == NULL)
216                                 {
217                                 if ((buf=BUF_MEM_new()) == NULL)
218                                         {
219                                         ret= -1;
220                                         goto end;
221                                         }
222                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
223                                         {
224                                         ret= -1;
225                                         goto end;
226                                         }
227                                 s->init_buf=buf;
228                                 buf=NULL;
229                                 }
230
231                         if (!ssl3_setup_buffers(s)) { ret= -1; goto end; }
232
233                         /* setup buffing BIO */
234                         if (!ssl_init_wbio_buffer(s,0)) { ret= -1; goto end; }
235
236                         /* don't push the buffering BIO quite yet */
237
238                         ssl3_init_finished_mac(s);
239
240                         s->state=SSL3_ST_CW_CLNT_HELLO_A;
241                         s->ctx->stats.sess_connect++;
242                         s->init_num=0;
243                         break;
244
245                 case SSL3_ST_CW_CLNT_HELLO_A:
246                 case SSL3_ST_CW_CLNT_HELLO_B:
247
248                         s->shutdown=0;
249                         ret=ssl3_client_hello(s);
250                         if (ret <= 0) goto end;
251                         s->state=SSL3_ST_CR_SRVR_HELLO_A;
252                         s->init_num=0;
253
254                         /* turn on buffering for the next lot of output */
255                         if (s->bbio != s->wbio)
256                                 s->wbio=BIO_push(s->bbio,s->wbio);
257
258                         break;
259
260                 case SSL3_ST_CR_SRVR_HELLO_A:
261                 case SSL3_ST_CR_SRVR_HELLO_B:
262                         ret=ssl3_get_server_hello(s);
263                         if (ret <= 0) goto end;
264                         if (s->hit)
265                                 {
266                                 s->state=SSL3_ST_CR_FINISHED_A;
267 #ifndef OPENSSL_NO_TLSEXT
268                                 if (s->tlsext_ticket_expected)
269                                         {
270                                         /* receive renewed session ticket */
271                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
272                                         }
273 #endif
274                                 }
275                         else
276                                 s->state=SSL3_ST_CR_CERT_A;
277                         s->init_num=0;
278                         break;
279
280                 case SSL3_ST_CR_CERT_A:
281                 case SSL3_ST_CR_CERT_B:
282 #ifndef OPENSSL_NO_TLSEXT
283                         ret=ssl3_check_finished(s);
284                         if (ret <= 0) goto end;
285                         if (ret == 2)
286                                 {
287                                 s->hit = 1;
288                                 if (s->tlsext_ticket_expected)
289                                         s->state=SSL3_ST_CR_SESSION_TICKET_A;
290                                 else
291                                         s->state=SSL3_ST_CR_FINISHED_A;
292                                 s->init_num=0;
293                                 break;
294                                 }
295 #endif
296                         /* Check if it is anon DH/ECDH */
297                         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
298                                 {
299                                 ret=ssl3_get_server_certificate(s);
300                                 if (ret <= 0) goto end;
301 #ifndef OPENSSL_NO_TLSEXT
302                                 if (s->tlsext_status_expected)
303                                         s->state=SSL3_ST_CR_CERT_STATUS_A;
304                                 else
305                                         s->state=SSL3_ST_CR_KEY_EXCH_A;
306                                 }
307                         else
308                                 {
309                                 skip = 1;
310                                 s->state=SSL3_ST_CR_KEY_EXCH_A;
311                                 }
312 #else
313                                 }
314                         else
315                                 skip=1;
316
317                         s->state=SSL3_ST_CR_KEY_EXCH_A;
318 #endif
319                         s->init_num=0;
320                         break;
321
322                 case SSL3_ST_CR_KEY_EXCH_A:
323                 case SSL3_ST_CR_KEY_EXCH_B:
324                         ret=ssl3_get_key_exchange(s);
325                         if (ret <= 0) goto end;
326                         s->state=SSL3_ST_CR_CERT_REQ_A;
327                         s->init_num=0;
328
329                         /* at this point we check that we have the
330                          * required stuff from the server */
331                         if (!ssl3_check_cert_and_algorithm(s))
332                                 {
333                                 ret= -1;
334                                 goto end;
335                                 }
336                         break;
337
338                 case SSL3_ST_CR_CERT_REQ_A:
339                 case SSL3_ST_CR_CERT_REQ_B:
340                         ret=ssl3_get_certificate_request(s);
341                         if (ret <= 0) goto end;
342                         s->state=SSL3_ST_CR_SRVR_DONE_A;
343                         s->init_num=0;
344                         break;
345
346                 case SSL3_ST_CR_SRVR_DONE_A:
347                 case SSL3_ST_CR_SRVR_DONE_B:
348                         ret=ssl3_get_server_done(s);
349                         if (ret <= 0) goto end;
350                         if (s->s3->tmp.cert_req)
351                                 s->state=SSL3_ST_CW_CERT_A;
352                         else
353                                 s->state=SSL3_ST_CW_KEY_EXCH_A;
354                         s->init_num=0;
355
356                         break;
357
358                 case SSL3_ST_CW_CERT_A:
359                 case SSL3_ST_CW_CERT_B:
360                 case SSL3_ST_CW_CERT_C:
361                 case SSL3_ST_CW_CERT_D:
362                         ret=ssl3_send_client_certificate(s);
363                         if (ret <= 0) goto end;
364                         s->state=SSL3_ST_CW_KEY_EXCH_A;
365                         s->init_num=0;
366                         break;
367
368                 case SSL3_ST_CW_KEY_EXCH_A:
369                 case SSL3_ST_CW_KEY_EXCH_B:
370                         ret=ssl3_send_client_key_exchange(s);
371                         if (ret <= 0) goto end;
372                         /* EAY EAY EAY need to check for DH fix cert
373                          * sent back */
374                         /* For TLS, cert_req is set to 2, so a cert chain
375                          * of nothing is sent, but no verify packet is sent */
376                         /* XXX: For now, we do not support client 
377                          * authentication in ECDH cipher suites with
378                          * ECDH (rather than ECDSA) certificates.
379                          * We need to skip the certificate verify 
380                          * message when client's ECDH public key is sent 
381                          * inside the client certificate.
382                          */
383                         if (s->s3->tmp.cert_req == 1)
384                                 {
385                                 s->state=SSL3_ST_CW_CERT_VRFY_A;
386                                 }
387                         else
388                                 {
389                                 s->state=SSL3_ST_CW_CHANGE_A;
390                                 s->s3->change_cipher_spec=0;
391                                 }
392
393                         s->init_num=0;
394                         break;
395
396                 case SSL3_ST_CW_CERT_VRFY_A:
397                 case SSL3_ST_CW_CERT_VRFY_B:
398                         ret=ssl3_send_client_verify(s);
399                         if (ret <= 0) goto end;
400                         s->state=SSL3_ST_CW_CHANGE_A;
401                         s->init_num=0;
402                         s->s3->change_cipher_spec=0;
403                         break;
404
405                 case SSL3_ST_CW_CHANGE_A:
406                 case SSL3_ST_CW_CHANGE_B:
407                         ret=ssl3_send_change_cipher_spec(s,
408                                 SSL3_ST_CW_CHANGE_A,SSL3_ST_CW_CHANGE_B);
409                         if (ret <= 0) goto end;
410                         s->state=SSL3_ST_CW_FINISHED_A;
411                         s->init_num=0;
412
413                         s->session->cipher=s->s3->tmp.new_cipher;
414 #ifdef OPENSSL_NO_COMP
415                         s->session->compress_meth=0;
416 #else
417                         if (s->s3->tmp.new_compression == NULL)
418                                 s->session->compress_meth=0;
419                         else
420                                 s->session->compress_meth=
421                                         s->s3->tmp.new_compression->id;
422 #endif
423                         if (!s->method->ssl3_enc->setup_key_block(s))
424                                 {
425                                 ret= -1;
426                                 goto end;
427                                 }
428
429                         if (!s->method->ssl3_enc->change_cipher_state(s,
430                                 SSL3_CHANGE_CIPHER_CLIENT_WRITE))
431                                 {
432                                 ret= -1;
433                                 goto end;
434                                 }
435
436                         break;
437
438                 case SSL3_ST_CW_FINISHED_A:
439                 case SSL3_ST_CW_FINISHED_B:
440                         ret=ssl3_send_finished(s,
441                                 SSL3_ST_CW_FINISHED_A,SSL3_ST_CW_FINISHED_B,
442                                 s->method->ssl3_enc->client_finished_label,
443                                 s->method->ssl3_enc->client_finished_label_len);
444                         if (ret <= 0) goto end;
445                         s->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         if (s->s3->tmp.message_type != SSL3_MT_SERVER_KEY_EXCHANGE)
1126                 {
1127                 s->s3->tmp.reuse_message=1;
1128                 return(1);
1129                 }
1130
1131         param=p=(unsigned char *)s->init_msg;
1132
1133         if (s->session->sess_cert != NULL)
1134                 {
1135 #ifndef OPENSSL_NO_RSA
1136                 if (s->session->sess_cert->peer_rsa_tmp != NULL)
1137                         {
1138                         RSA_free(s->session->sess_cert->peer_rsa_tmp);
1139                         s->session->sess_cert->peer_rsa_tmp=NULL;
1140                         }
1141 #endif
1142 #ifndef OPENSSL_NO_DH
1143                 if (s->session->sess_cert->peer_dh_tmp)
1144                         {
1145                         DH_free(s->session->sess_cert->peer_dh_tmp);
1146                         s->session->sess_cert->peer_dh_tmp=NULL;
1147                         }
1148 #endif
1149 #ifndef OPENSSL_NO_ECDH
1150                 if (s->session->sess_cert->peer_ecdh_tmp)
1151                         {
1152                         EC_KEY_free(s->session->sess_cert->peer_ecdh_tmp);
1153                         s->session->sess_cert->peer_ecdh_tmp=NULL;
1154                         }
1155 #endif
1156                 }
1157         else
1158                 {
1159                 s->session->sess_cert=ssl_sess_cert_new();
1160                 }
1161
1162         param_len=0;
1163         alg=s->s3->tmp.new_cipher->algorithms;
1164         EVP_MD_CTX_init(&md_ctx);
1165
1166 #ifndef OPENSSL_NO_RSA
1167         if (alg & SSL_kRSA)
1168                 {
1169                 if ((rsa=RSA_new()) == NULL)
1170                         {
1171                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1172                         goto err;
1173                         }
1174                 n2s(p,i);
1175                 param_len=i+2;
1176                 if (param_len > n)
1177                         {
1178                         al=SSL_AD_DECODE_ERROR;
1179                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_MODULUS_LENGTH);
1180                         goto f_err;
1181                         }
1182                 if (!(rsa->n=BN_bin2bn(p,i,rsa->n)))
1183                         {
1184                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1185                         goto err;
1186                         }
1187                 p+=i;
1188
1189                 n2s(p,i);
1190                 param_len+=i+2;
1191                 if (param_len > n)
1192                         {
1193                         al=SSL_AD_DECODE_ERROR;
1194                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_E_LENGTH);
1195                         goto f_err;
1196                         }
1197                 if (!(rsa->e=BN_bin2bn(p,i,rsa->e)))
1198                         {
1199                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1200                         goto err;
1201                         }
1202                 p+=i;
1203                 n-=param_len;
1204
1205                 /* this should be because we are using an export cipher */
1206                 if (alg & SSL_aRSA)
1207                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1208                 else
1209                         {
1210                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1211                         goto err;
1212                         }
1213                 s->session->sess_cert->peer_rsa_tmp=rsa;
1214                 rsa=NULL;
1215                 }
1216 #else /* OPENSSL_NO_RSA */
1217         if (0)
1218                 ;
1219 #endif
1220 #ifndef OPENSSL_NO_DH
1221         else if (alg & SSL_kEDH)
1222                 {
1223                 if ((dh=DH_new()) == NULL)
1224                         {
1225                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_DH_LIB);
1226                         goto err;
1227                         }
1228                 n2s(p,i);
1229                 param_len=i+2;
1230                 if (param_len > n)
1231                         {
1232                         al=SSL_AD_DECODE_ERROR;
1233                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_P_LENGTH);
1234                         goto f_err;
1235                         }
1236                 if (!(dh->p=BN_bin2bn(p,i,NULL)))
1237                         {
1238                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1239                         goto err;
1240                         }
1241                 p+=i;
1242
1243                 n2s(p,i);
1244                 param_len+=i+2;
1245                 if (param_len > n)
1246                         {
1247                         al=SSL_AD_DECODE_ERROR;
1248                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_G_LENGTH);
1249                         goto f_err;
1250                         }
1251                 if (!(dh->g=BN_bin2bn(p,i,NULL)))
1252                         {
1253                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1254                         goto err;
1255                         }
1256                 p+=i;
1257
1258                 n2s(p,i);
1259                 param_len+=i+2;
1260                 if (param_len > n)
1261                         {
1262                         al=SSL_AD_DECODE_ERROR;
1263                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_DH_PUB_KEY_LENGTH);
1264                         goto f_err;
1265                         }
1266                 if (!(dh->pub_key=BN_bin2bn(p,i,NULL)))
1267                         {
1268                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_BN_LIB);
1269                         goto err;
1270                         }
1271                 p+=i;
1272                 n-=param_len;
1273
1274 #ifndef OPENSSL_NO_RSA
1275                 if (alg & SSL_aRSA)
1276                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1277 #else
1278                 if (0)
1279                         ;
1280 #endif
1281 #ifndef OPENSSL_NO_DSA
1282                 else if (alg & SSL_aDSS)
1283                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_DSA_SIGN].x509);
1284 #endif
1285                 /* else anonymous DH, so no certificate or pkey. */
1286
1287                 s->session->sess_cert->peer_dh_tmp=dh;
1288                 dh=NULL;
1289                 }
1290         else if ((alg & SSL_kDHr) || (alg & SSL_kDHd))
1291                 {
1292                 al=SSL_AD_ILLEGAL_PARAMETER;
1293                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1294                 goto f_err;
1295                 }
1296 #endif /* !OPENSSL_NO_DH */
1297
1298 #ifndef OPENSSL_NO_ECDH
1299         else if (alg & SSL_kECDHE)
1300                 {
1301                 EC_GROUP *ngroup;
1302                 const EC_GROUP *group;
1303
1304                 if ((ecdh=EC_KEY_new()) == NULL)
1305                         {
1306                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1307                         goto err;
1308                         }
1309
1310                 /* Extract elliptic curve parameters and the
1311                  * server's ephemeral ECDH public key.
1312                  * Keep accumulating lengths of various components in
1313                  * param_len and make sure it never exceeds n.
1314                  */
1315
1316                 /* XXX: For now we only support named (not generic) curves
1317                  * and the ECParameters in this case is just three bytes.
1318                  */
1319                 param_len=3;
1320                 if ((param_len > n) ||
1321                     (*p != NAMED_CURVE_TYPE) || 
1322                     ((curve_nid = curve_id2nid(*(p + 2))) == 0)) 
1323                         {
1324                         al=SSL_AD_INTERNAL_ERROR;
1325                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_ECDH_PARAMETERS);
1326                         goto f_err;
1327                         }
1328
1329                 ngroup = EC_GROUP_new_by_curve_name(curve_nid);
1330                 if (ngroup == NULL)
1331                         {
1332                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1333                         goto err;
1334                         }
1335                 if (EC_KEY_set_group(ecdh, ngroup) == 0)
1336                         {
1337                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_EC_LIB);
1338                         goto err;
1339                         }
1340                 EC_GROUP_free(ngroup);
1341
1342                 group = EC_KEY_get0_group(ecdh);
1343
1344                 if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1345                     (EC_GROUP_get_degree(group) > 163))
1346                         {
1347                         al=SSL_AD_EXPORT_RESTRICTION;
1348                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1349                         goto f_err;
1350                         }
1351
1352                 p+=3;
1353
1354                 /* Next, get the encoded ECPoint */
1355                 if (((srvr_ecpoint = EC_POINT_new(group)) == NULL) ||
1356                     ((bn_ctx = BN_CTX_new()) == NULL))
1357                         {
1358                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1359                         goto err;
1360                         }
1361
1362                 encoded_pt_len = *p;  /* length of encoded point */
1363                 p+=1;
1364                 param_len += (1 + encoded_pt_len);
1365                 if ((param_len > n) ||
1366                     (EC_POINT_oct2point(group, srvr_ecpoint, 
1367                         p, encoded_pt_len, bn_ctx) == 0))
1368                         {
1369                         al=SSL_AD_DECODE_ERROR;
1370                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_ECPOINT);
1371                         goto f_err;
1372                         }
1373
1374                 n-=param_len;
1375                 p+=encoded_pt_len;
1376
1377                 /* The ECC/TLS specification does not mention
1378                  * the use of DSA to sign ECParameters in the server
1379                  * key exchange message. We do support RSA and ECDSA.
1380                  */
1381                 if (0) ;
1382 #ifndef OPENSSL_NO_RSA
1383                 else if (alg & SSL_aRSA)
1384                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1385 #endif
1386 #ifndef OPENSSL_NO_ECDSA
1387                 else if (alg & SSL_aECDSA)
1388                         pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
1389 #endif
1390                 /* else anonymous ECDH, so no certificate or pkey. */
1391                 EC_KEY_set_public_key(ecdh, srvr_ecpoint);
1392                 s->session->sess_cert->peer_ecdh_tmp=ecdh;
1393                 ecdh=NULL;
1394                 BN_CTX_free(bn_ctx);
1395                 bn_ctx = NULL;
1396                 EC_POINT_free(srvr_ecpoint);
1397                 srvr_ecpoint = NULL;
1398                 }
1399         else if (alg & SSL_kECDH)
1400                 {
1401                 al=SSL_AD_UNEXPECTED_MESSAGE;
1402                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
1403                 goto f_err;
1404                 }
1405 #endif /* !OPENSSL_NO_ECDH */
1406         if (alg & SSL_aFZA)
1407                 {
1408                 al=SSL_AD_HANDSHAKE_FAILURE;
1409                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_TRIED_TO_USE_UNSUPPORTED_CIPHER);
1410                 goto f_err;
1411                 }
1412
1413
1414         /* p points to the next byte, there are 'n' bytes left */
1415
1416         /* if it was signed, check the signature */
1417         if (pkey != NULL)
1418                 {
1419                 n2s(p,i);
1420                 n-=2;
1421                 j=EVP_PKEY_size(pkey);
1422
1423                 if ((i != n) || (n > j) || (n <= 0))
1424                         {
1425                         /* wrong packet length */
1426                         al=SSL_AD_DECODE_ERROR;
1427                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_WRONG_SIGNATURE_LENGTH);
1428                         goto f_err;
1429                         }
1430
1431 #ifndef OPENSSL_NO_RSA
1432                 if (pkey->type == EVP_PKEY_RSA)
1433                         {
1434                         int num;
1435
1436                         j=0;
1437                         q=md_buf;
1438                         for (num=2; num > 0; num--)
1439                                 {
1440                                 EVP_MD_CTX_set_flags(&md_ctx,
1441                                         EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1442                                 EVP_DigestInit_ex(&md_ctx,(num == 2)
1443                                         ?s->ctx->md5:s->ctx->sha1, NULL);
1444                                 EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1445                                 EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1446                                 EVP_DigestUpdate(&md_ctx,param,param_len);
1447                                 EVP_DigestFinal_ex(&md_ctx,q,(unsigned int *)&i);
1448                                 q+=i;
1449                                 j+=i;
1450                                 }
1451                         i=RSA_verify(NID_md5_sha1, md_buf, j, p, n,
1452                                                                 pkey->pkey.rsa);
1453                         if (i < 0)
1454                                 {
1455                                 al=SSL_AD_DECRYPT_ERROR;
1456                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT);
1457                                 goto f_err;
1458                                 }
1459                         if (i == 0)
1460                                 {
1461                                 /* bad signature */
1462                                 al=SSL_AD_DECRYPT_ERROR;
1463                                 SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_BAD_SIGNATURE);
1464                                 goto f_err;
1465                                 }
1466                         }
1467                 else
1468 #endif
1469 #ifndef OPENSSL_NO_DSA
1470                         if (pkey->type == EVP_PKEY_DSA)
1471                         {
1472                         /* lets do DSS */
1473                         EVP_VerifyInit_ex(&md_ctx,EVP_dss1(), NULL);
1474                         EVP_VerifyUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1475                         EVP_VerifyUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1476                         EVP_VerifyUpdate(&md_ctx,param,param_len);
1477                         if (EVP_VerifyFinal(&md_ctx,p,(int)n,pkey) <= 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_ECDSA
1488                         if (pkey->type == EVP_PKEY_EC)
1489                         {
1490                         /* let's do ECDSA */
1491                         EVP_VerifyInit_ex(&md_ctx,EVP_ecdsa(), 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                         {
1506                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1507                         goto err;
1508                         }
1509                 }
1510         else
1511                 {
1512                 /* still data left over */
1513                 if (!(alg & SSL_aNULL))
1514                         {
1515                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1516                         goto err;
1517                         }
1518                 if (n != 0)
1519                         {
1520                         al=SSL_AD_DECODE_ERROR;
1521                         SSLerr(SSL_F_SSL3_GET_KEY_EXCHANGE,SSL_R_EXTRA_DATA_IN_MESSAGE);
1522                         goto f_err;
1523                         }
1524                 }
1525         EVP_PKEY_free(pkey);
1526         EVP_MD_CTX_cleanup(&md_ctx);
1527         return(1);
1528 f_err:
1529         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1530 err:
1531         EVP_PKEY_free(pkey);
1532 #ifndef OPENSSL_NO_RSA
1533         if (rsa != NULL)
1534                 RSA_free(rsa);
1535 #endif
1536 #ifndef OPENSSL_NO_DH
1537         if (dh != NULL)
1538                 DH_free(dh);
1539 #endif
1540 #ifndef OPENSSL_NO_ECDH
1541         BN_CTX_free(bn_ctx);
1542         EC_POINT_free(srvr_ecpoint);
1543         if (ecdh != NULL)
1544                 EC_KEY_free(ecdh);
1545 #endif
1546         EVP_MD_CTX_cleanup(&md_ctx);
1547         return(-1);
1548         }
1549
1550 int ssl3_get_certificate_request(SSL *s)
1551         {
1552         int ok,ret=0;
1553         unsigned long n,nc,l;
1554         unsigned int llen,ctype_num,i;
1555         X509_NAME *xn=NULL;
1556         const unsigned char *p,*q;
1557         unsigned char *d;
1558         STACK_OF(X509_NAME) *ca_sk=NULL;
1559
1560         n=s->method->ssl_get_message(s,
1561                 SSL3_ST_CR_CERT_REQ_A,
1562                 SSL3_ST_CR_CERT_REQ_B,
1563                 -1,
1564                 s->max_cert_list,
1565                 &ok);
1566
1567         if (!ok) return((int)n);
1568
1569         s->s3->tmp.cert_req=0;
1570
1571         if (s->s3->tmp.message_type == SSL3_MT_SERVER_DONE)
1572                 {
1573                 s->s3->tmp.reuse_message=1;
1574                 return(1);
1575                 }
1576
1577         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_REQUEST)
1578                 {
1579                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1580                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_WRONG_MESSAGE_TYPE);
1581                 goto err;
1582                 }
1583
1584         /* TLS does not like anon-DH with client cert */
1585         if (s->version > SSL3_VERSION)
1586                 {
1587                 l=s->s3->tmp.new_cipher->algorithms;
1588                 if (l & SSL_aNULL)
1589                         {
1590                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
1591                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_TLS_CLIENT_CERT_REQ_WITH_ANON_CIPHER);
1592                         goto err;
1593                         }
1594                 }
1595
1596         p=d=(unsigned char *)s->init_msg;
1597
1598         if ((ca_sk=sk_X509_NAME_new(ca_dn_cmp)) == NULL)
1599                 {
1600                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1601                 goto err;
1602                 }
1603
1604         /* get the certificate types */
1605         ctype_num= *(p++);
1606         if (ctype_num > SSL3_CT_NUMBER)
1607                 ctype_num=SSL3_CT_NUMBER;
1608         for (i=0; i<ctype_num; i++)
1609                 s->s3->tmp.ctype[i]= p[i];
1610         p+=ctype_num;
1611
1612         /* get the CA RDNs */
1613         n2s(p,llen);
1614 #if 0
1615 {
1616 FILE *out;
1617 out=fopen("/tmp/vsign.der","w");
1618 fwrite(p,1,llen,out);
1619 fclose(out);
1620 }
1621 #endif
1622
1623         if ((llen+ctype_num+2+1) != n)
1624                 {
1625                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1626                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_LENGTH_MISMATCH);
1627                 goto err;
1628                 }
1629
1630         for (nc=0; nc<llen; )
1631                 {
1632                 n2s(p,l);
1633                 if ((l+nc+2) > llen)
1634                         {
1635                         if ((s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1636                                 goto cont; /* netscape bugs */
1637                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1638                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_TOO_LONG);
1639                         goto err;
1640                         }
1641
1642                 q=p;
1643
1644                 if ((xn=d2i_X509_NAME(NULL,&q,l)) == NULL)
1645                         {
1646                         /* If netscape tolerance is on, ignore errors */
1647                         if (s->options & SSL_OP_NETSCAPE_CA_DN_BUG)
1648                                 goto cont;
1649                         else
1650                                 {
1651                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1652                                 SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_ASN1_LIB);
1653                                 goto err;
1654                                 }
1655                         }
1656
1657                 if (q != (p+l))
1658                         {
1659                         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1660                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,SSL_R_CA_DN_LENGTH_MISMATCH);
1661                         goto err;
1662                         }
1663                 if (!sk_X509_NAME_push(ca_sk,xn))
1664                         {
1665                         SSLerr(SSL_F_SSL3_GET_CERTIFICATE_REQUEST,ERR_R_MALLOC_FAILURE);
1666                         goto err;
1667                         }
1668
1669                 p+=l;
1670                 nc+=l+2;
1671                 }
1672
1673         if (0)
1674                 {
1675 cont:
1676                 ERR_clear_error();
1677                 }
1678
1679         /* we should setup a certificate to return.... */
1680         s->s3->tmp.cert_req=1;
1681         s->s3->tmp.ctype_num=ctype_num;
1682         if (s->s3->tmp.ca_names != NULL)
1683                 sk_X509_NAME_pop_free(s->s3->tmp.ca_names,X509_NAME_free);
1684         s->s3->tmp.ca_names=ca_sk;
1685         ca_sk=NULL;
1686
1687         ret=1;
1688 err:
1689         if (ca_sk != NULL) sk_X509_NAME_pop_free(ca_sk,X509_NAME_free);
1690         return(ret);
1691         }
1692
1693 static int ca_dn_cmp(const X509_NAME * const *a, const X509_NAME * const *b)
1694         {
1695         return(X509_NAME_cmp(*a,*b));
1696         }
1697 #ifndef OPENSSL_NO_TLSEXT
1698 int ssl3_get_new_session_ticket(SSL *s)
1699         {
1700         int ok,al,ret=0, ticklen;
1701         long n;
1702         const unsigned char *p;
1703         unsigned char *d;
1704
1705         n=s->method->ssl_get_message(s,
1706                 SSL3_ST_CR_SESSION_TICKET_A,
1707                 SSL3_ST_CR_SESSION_TICKET_B,
1708                 -1,
1709                 16384,
1710                 &ok);
1711
1712         if (!ok)
1713                 return((int)n);
1714
1715         if (s->s3->tmp.message_type == SSL3_MT_FINISHED)
1716                 {
1717                 s->s3->tmp.reuse_message=1;
1718                 return(1);
1719                 }
1720         if (s->s3->tmp.message_type != SSL3_MT_NEWSESSION_TICKET)
1721                 {
1722                 al=SSL_AD_UNEXPECTED_MESSAGE;
1723                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_BAD_MESSAGE_TYPE);
1724                 goto f_err;
1725                 }
1726         if (n < 6)
1727                 {
1728                 /* need at least ticket_lifetime_hint + ticket length */
1729                 al = SSL_AD_DECODE_ERROR;
1730                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
1731                 goto f_err;
1732                 }
1733
1734         p=d=(unsigned char *)s->init_msg;
1735         n2l(p, s->session->tlsext_tick_lifetime_hint);
1736         n2s(p, ticklen);
1737         /* ticket_lifetime_hint + ticket_length + ticket */
1738         if (ticklen + 6 != n)
1739                 {
1740                 al = SSL_AD_DECODE_ERROR;
1741                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,SSL_R_LENGTH_MISMATCH);
1742                 goto f_err;
1743                 }
1744         if (s->session->tlsext_tick)
1745                 {
1746                 OPENSSL_free(s->session->tlsext_tick);
1747                 s->session->tlsext_ticklen = 0;
1748                 }
1749         s->session->tlsext_tick = OPENSSL_malloc(ticklen);
1750         if (!s->session->tlsext_tick)
1751                 {
1752                 SSLerr(SSL_F_SSL3_GET_NEW_SESSION_TICKET,ERR_R_MALLOC_FAILURE);
1753                 goto err;
1754                 }
1755         memcpy(s->session->tlsext_tick, p, ticklen);
1756         s->session->tlsext_ticklen = ticklen;
1757         /* There are two ways to detect a resumed ticket sesion.
1758          * One is to set an appropriate session ID and then the server
1759          * must return a match in ServerHello. This allows the normal
1760          * client session ID matching to work and we know much 
1761          * earlier that the ticket has been accepted.
1762          * 
1763          * The other way is to set zero length session ID when the
1764          * ticket is presented and rely on the handshake to determine
1765          * session resumption.
1766          *
1767          * We choose the former approach because this fits in with
1768          * assumptions elsewhere in OpenSSL. The session ID is set
1769          * to the SHA256 (or SHA1 is SHA256 is disabled) hash of the
1770          * ticket.
1771          */ 
1772         EVP_Digest(p, ticklen,
1773                         s->session->session_id, &s->session->session_id_length,
1774 #ifndef OPENSSL_NO_SHA256
1775                                                         EVP_sha256(), NULL);
1776 #else
1777                                                         EVP_sha1(), NULL);
1778 #endif
1779         ret=1;
1780         return(ret);
1781 f_err:
1782         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1783 err:
1784         return(-1);
1785         }
1786
1787 int ssl3_get_cert_status(SSL *s)
1788         {
1789         int ok, al;
1790         unsigned long resplen;
1791         long n;
1792         const unsigned char *p;
1793
1794         n=s->method->ssl_get_message(s,
1795                 SSL3_ST_CR_CERT_STATUS_A,
1796                 SSL3_ST_CR_CERT_STATUS_B,
1797                 SSL3_MT_CERTIFICATE_STATUS,
1798                 16384,
1799                 &ok);
1800
1801         if (!ok) return((int)n);
1802         if (n < 4)
1803                 {
1804                 /* need at least status type + length */
1805                 al = SSL_AD_DECODE_ERROR;
1806                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
1807                 goto f_err;
1808                 }
1809         p = (unsigned char *)s->init_msg;
1810         if (*p++ != TLSEXT_STATUSTYPE_ocsp)
1811                 {
1812                 al = SSL_AD_DECODE_ERROR;
1813                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_UNSUPPORTED_STATUS_TYPE);
1814                 goto f_err;
1815                 }
1816         n2l3(p, resplen);
1817         if (resplen + 4 != (unsigned long)n)
1818                 {
1819                 al = SSL_AD_DECODE_ERROR;
1820                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_LENGTH_MISMATCH);
1821                 goto f_err;
1822                 }
1823         if (s->tlsext_ocsp_resp)
1824                 OPENSSL_free(s->tlsext_ocsp_resp);
1825         s->tlsext_ocsp_resp = BUF_memdup(p, resplen);
1826         if (!s->tlsext_ocsp_resp)
1827                 {
1828                 al = SSL_AD_INTERNAL_ERROR;
1829                 SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
1830                 goto f_err;
1831                 }
1832         s->tlsext_ocsp_resplen = resplen;
1833         if (s->ctx->tlsext_status_cb)
1834                 {
1835                 int ret;
1836                 ret = s->ctx->tlsext_status_cb(s, s->ctx->tlsext_status_arg);
1837                 if (ret == 0)
1838                         {
1839                         al = SSL_AD_BAD_CERTIFICATE_STATUS_RESPONSE;
1840                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,SSL_R_INVALID_STATUS_RESPONSE);
1841                         goto f_err;
1842                         }
1843                 if (ret < 0)
1844                         {
1845                         al = SSL_AD_INTERNAL_ERROR;
1846                         SSLerr(SSL_F_SSL3_GET_CERT_STATUS,ERR_R_MALLOC_FAILURE);
1847                         goto f_err;
1848                         }
1849                 }
1850         return 1;
1851 f_err:
1852         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1853         return(-1);
1854         }
1855 #endif
1856
1857 int ssl3_get_server_done(SSL *s)
1858         {
1859         int ok,ret=0;
1860         long n;
1861
1862         n=s->method->ssl_get_message(s,
1863                 SSL3_ST_CR_SRVR_DONE_A,
1864                 SSL3_ST_CR_SRVR_DONE_B,
1865                 SSL3_MT_SERVER_DONE,
1866                 30, /* should be very small, like 0 :-) */
1867                 &ok);
1868
1869         if (!ok) return((int)n);
1870         if (n > 0)
1871                 {
1872                 /* should contain no data */
1873                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_DECODE_ERROR);
1874                 SSLerr(SSL_F_SSL3_GET_SERVER_DONE,SSL_R_LENGTH_MISMATCH);
1875                 return -1;
1876                 }
1877         ret=1;
1878         return(ret);
1879         }
1880
1881
1882 int ssl3_send_client_key_exchange(SSL *s)
1883         {
1884         unsigned char *p,*d;
1885         int n;
1886         unsigned long l;
1887 #ifndef OPENSSL_NO_RSA
1888         unsigned char *q;
1889         EVP_PKEY *pkey=NULL;
1890 #endif
1891 #ifndef OPENSSL_NO_KRB5
1892         KSSL_ERR kssl_err;
1893 #endif /* OPENSSL_NO_KRB5 */
1894 #ifndef OPENSSL_NO_ECDH
1895         EC_KEY *clnt_ecdh = NULL;
1896         const EC_POINT *srvr_ecpoint = NULL;
1897         EVP_PKEY *srvr_pub_pkey = NULL;
1898         unsigned char *encodedPoint = NULL;
1899         int encoded_pt_len = 0;
1900         BN_CTX * bn_ctx = NULL;
1901 #endif
1902
1903         if (s->state == SSL3_ST_CW_KEY_EXCH_A)
1904                 {
1905                 d=(unsigned char *)s->init_buf->data;
1906                 p= &(d[4]);
1907
1908                 l=s->s3->tmp.new_cipher->algorithms;
1909
1910                 /* Fool emacs indentation */
1911                 if (0) {}
1912 #ifndef OPENSSL_NO_RSA
1913                 else if (l & SSL_kRSA)
1914                         {
1915                         RSA *rsa;
1916                         unsigned char tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1917
1918                         if (s->session->sess_cert->peer_rsa_tmp != NULL)
1919                                 rsa=s->session->sess_cert->peer_rsa_tmp;
1920                         else
1921                                 {
1922                                 pkey=X509_get_pubkey(s->session->sess_cert->peer_pkeys[SSL_PKEY_RSA_ENC].x509);
1923                                 if ((pkey == NULL) ||
1924                                         (pkey->type != EVP_PKEY_RSA) ||
1925                                         (pkey->pkey.rsa == NULL))
1926                                         {
1927                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1928                                         goto err;
1929                                         }
1930                                 rsa=pkey->pkey.rsa;
1931                                 EVP_PKEY_free(pkey);
1932                                 }
1933                                 
1934                         tmp_buf[0]=s->client_version>>8;
1935                         tmp_buf[1]=s->client_version&0xff;
1936                         if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
1937                                         goto err;
1938
1939                         s->session->master_key_length=sizeof tmp_buf;
1940
1941                         q=p;
1942                         /* Fix buf for TLS and beyond */
1943                         if (s->version > SSL3_VERSION)
1944                                 p+=2;
1945                         n=RSA_public_encrypt(sizeof tmp_buf,
1946                                 tmp_buf,p,rsa,RSA_PKCS1_PADDING);
1947 #ifdef PKCS1_CHECK
1948                         if (s->options & SSL_OP_PKCS1_CHECK_1) p[1]++;
1949                         if (s->options & SSL_OP_PKCS1_CHECK_2) tmp_buf[0]=0x70;
1950 #endif
1951                         if (n <= 0)
1952                                 {
1953                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_ENCRYPT);
1954                                 goto err;
1955                                 }
1956
1957                         /* Fix buf for TLS and beyond */
1958                         if (s->version > SSL3_VERSION)
1959                                 {
1960                                 s2n(n,q);
1961                                 n+=2;
1962                                 }
1963
1964                         s->session->master_key_length=
1965                                 s->method->ssl3_enc->generate_master_secret(s,
1966                                         s->session->master_key,
1967                                         tmp_buf,sizeof tmp_buf);
1968                         OPENSSL_cleanse(tmp_buf,sizeof tmp_buf);
1969                         }
1970 #endif
1971 #ifndef OPENSSL_NO_KRB5
1972                 else if (l & SSL_kKRB5)
1973                         {
1974                         krb5_error_code krb5rc;
1975                         KSSL_CTX        *kssl_ctx = s->kssl_ctx;
1976                         /*  krb5_data   krb5_ap_req;  */
1977                         krb5_data       *enc_ticket;
1978                         krb5_data       authenticator, *authp = NULL;
1979                         EVP_CIPHER_CTX  ciph_ctx;
1980                         EVP_CIPHER      *enc = NULL;
1981                         unsigned char   iv[EVP_MAX_IV_LENGTH];
1982                         unsigned char   tmp_buf[SSL_MAX_MASTER_KEY_LENGTH];
1983                         unsigned char   epms[SSL_MAX_MASTER_KEY_LENGTH 
1984                                                 + EVP_MAX_IV_LENGTH];
1985                         int             padl, outl = sizeof(epms);
1986
1987                         EVP_CIPHER_CTX_init(&ciph_ctx);
1988
1989 #ifdef KSSL_DEBUG
1990                         printf("ssl3_send_client_key_exchange(%lx & %lx)\n",
1991                                 l, SSL_kKRB5);
1992 #endif  /* KSSL_DEBUG */
1993
1994                         authp = NULL;
1995 #ifdef KRB5SENDAUTH
1996                         if (KRB5SENDAUTH)  authp = &authenticator;
1997 #endif  /* KRB5SENDAUTH */
1998
1999                         krb5rc = kssl_cget_tkt(kssl_ctx, &enc_ticket, authp,
2000                                 &kssl_err);
2001                         enc = kssl_map_enc(kssl_ctx->enctype);
2002                         if (enc == NULL)
2003                             goto err;
2004 #ifdef KSSL_DEBUG
2005                         {
2006                         printf("kssl_cget_tkt rtn %d\n", krb5rc);
2007                         if (krb5rc && kssl_err.text)
2008                           printf("kssl_cget_tkt kssl_err=%s\n", kssl_err.text);
2009                         }
2010 #endif  /* KSSL_DEBUG */
2011
2012                         if (krb5rc)
2013                                 {
2014                                 ssl3_send_alert(s,SSL3_AL_FATAL,
2015                                                 SSL_AD_HANDSHAKE_FAILURE);
2016                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2017                                                 kssl_err.reason);
2018                                 goto err;
2019                                 }
2020
2021                         /*  20010406 VRS - Earlier versions used KRB5 AP_REQ
2022                         **  in place of RFC 2712 KerberosWrapper, as in:
2023                         **
2024                         **  Send ticket (copy to *p, set n = length)
2025                         **  n = krb5_ap_req.length;
2026                         **  memcpy(p, krb5_ap_req.data, krb5_ap_req.length);
2027                         **  if (krb5_ap_req.data)  
2028                         **    kssl_krb5_free_data_contents(NULL,&krb5_ap_req);
2029                         **
2030                         **  Now using real RFC 2712 KerberosWrapper
2031                         **  (Thanks to Simon Wilkinson <sxw@sxw.org.uk>)
2032                         **  Note: 2712 "opaque" types are here replaced
2033                         **  with a 2-byte length followed by the value.
2034                         **  Example:
2035                         **  KerberosWrapper= xx xx asn1ticket 0 0 xx xx encpms
2036                         **  Where "xx xx" = length bytes.  Shown here with
2037                         **  optional authenticator omitted.
2038                         */
2039
2040                         /*  KerberosWrapper.Ticket              */
2041                         s2n(enc_ticket->length,p);
2042                         memcpy(p, enc_ticket->data, enc_ticket->length);
2043                         p+= enc_ticket->length;
2044                         n = enc_ticket->length + 2;
2045
2046                         /*  KerberosWrapper.Authenticator       */
2047                         if (authp  &&  authp->length)  
2048                                 {
2049                                 s2n(authp->length,p);
2050                                 memcpy(p, authp->data, authp->length);
2051                                 p+= authp->length;
2052                                 n+= authp->length + 2;
2053                                 
2054                                 free(authp->data);
2055                                 authp->data = NULL;
2056                                 authp->length = 0;
2057                                 }
2058                         else
2059                                 {
2060                                 s2n(0,p);/*  null authenticator length  */
2061                                 n+=2;
2062                                 }
2063  
2064                             tmp_buf[0]=s->client_version>>8;
2065                             tmp_buf[1]=s->client_version&0xff;
2066                             if (RAND_bytes(&(tmp_buf[2]),sizeof tmp_buf-2) <= 0)
2067                                 goto err;
2068
2069                         /*  20010420 VRS.  Tried it this way; failed.
2070                         **      EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,NULL);
2071                         **      EVP_CIPHER_CTX_set_key_length(&ciph_ctx,
2072                         **                              kssl_ctx->length);
2073                         **      EVP_EncryptInit_ex(&ciph_ctx,NULL, key,iv);
2074                         */
2075
2076                         memset(iv, 0, sizeof iv);  /* per RFC 1510 */
2077                         EVP_EncryptInit_ex(&ciph_ctx,enc, NULL,
2078                                 kssl_ctx->key,iv);
2079                         EVP_EncryptUpdate(&ciph_ctx,epms,&outl,tmp_buf,
2080                                 sizeof tmp_buf);
2081                         EVP_EncryptFinal_ex(&ciph_ctx,&(epms[outl]),&padl);
2082                         outl += padl;
2083                         if (outl > sizeof epms)
2084                                 {
2085                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
2086                                 goto err;
2087                                 }
2088                         EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2089
2090                         /*  KerberosWrapper.EncryptedPreMasterSecret    */
2091                         s2n(outl,p);
2092                         memcpy(p, epms, outl);
2093                         p+=outl;
2094                         n+=outl + 2;
2095
2096                         s->session->master_key_length=
2097                                 s->method->ssl3_enc->generate_master_secret(s,
2098                                         s->session->master_key,
2099                                         tmp_buf, sizeof tmp_buf);
2100
2101                         OPENSSL_cleanse(tmp_buf, sizeof tmp_buf);
2102                         OPENSSL_cleanse(epms, outl);
2103                         }
2104 #endif
2105 #ifndef OPENSSL_NO_DH
2106                 else if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2107                         {
2108                         DH *dh_srvr,*dh_clnt;
2109
2110                         if (s->session->sess_cert == NULL) 
2111                                 {
2112                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_UNEXPECTED_MESSAGE);
2113                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNEXPECTED_MESSAGE);
2114                                 goto err;
2115                                 }
2116
2117                         if (s->session->sess_cert->peer_dh_tmp != NULL)
2118                                 dh_srvr=s->session->sess_cert->peer_dh_tmp;
2119                         else
2120                                 {
2121                                 /* we get them from the cert */
2122                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2123                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_FIND_DH_PARAMETERS);
2124                                 goto err;
2125                                 }
2126                         
2127                         /* generate a new random key */
2128                         if ((dh_clnt=DHparams_dup(dh_srvr)) == NULL)
2129                                 {
2130                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2131                                 goto err;
2132                                 }
2133                         if (!DH_generate_key(dh_clnt))
2134                                 {
2135                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2136                                 goto err;
2137                                 }
2138
2139                         /* use the 'p' output buffer for the DH key, but
2140                          * make sure to clear it out afterwards */
2141
2142                         n=DH_compute_key(p,dh_srvr->pub_key,dh_clnt);
2143
2144                         if (n <= 0)
2145                                 {
2146                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2147                                 goto err;
2148                                 }
2149
2150                         /* generate master key from the result */
2151                         s->session->master_key_length=
2152                                 s->method->ssl3_enc->generate_master_secret(s,
2153                                         s->session->master_key,p,n);
2154                         /* clean up */
2155                         memset(p,0,n);
2156
2157                         /* send off the data */
2158                         n=BN_num_bytes(dh_clnt->pub_key);
2159                         s2n(n,p);
2160                         BN_bn2bin(dh_clnt->pub_key,p);
2161                         n+=2;
2162
2163                         DH_free(dh_clnt);
2164
2165                         /* perhaps clean things up a bit EAY EAY EAY EAY*/
2166                         }
2167 #endif
2168
2169 #ifndef OPENSSL_NO_ECDH 
2170                 else if ((l & SSL_kECDH) || (l & SSL_kECDHE))
2171                         {
2172                         const EC_GROUP *srvr_group = NULL;
2173                         EC_KEY *tkey;
2174                         int ecdh_clnt_cert = 0;
2175                         int field_size = 0;
2176
2177                         /* Did we send out the client's
2178                          * ECDH share for use in premaster
2179                          * computation as part of client certificate?
2180                          * If so, set ecdh_clnt_cert to 1.
2181                          */
2182                         if ((l & SSL_kECDH) && (s->cert != NULL)) 
2183                                 {
2184                                 /* XXX: For now, we do not support client
2185                                  * authentication using ECDH certificates.
2186                                  * To add such support, one needs to add
2187                                  * code that checks for appropriate 
2188                                  * conditions and sets ecdh_clnt_cert to 1.
2189                                  * For example, the cert have an ECC
2190                                  * key on the same curve as the server's
2191                                  * and the key should be authorized for
2192                                  * key agreement.
2193                                  *
2194                                  * One also needs to add code in ssl3_connect
2195                                  * to skip sending the certificate verify
2196                                  * message.
2197                                  *
2198                                  * if ((s->cert->key->privatekey != NULL) &&
2199                                  *     (s->cert->key->privatekey->type ==
2200                                  *      EVP_PKEY_EC) && ...)
2201                                  * ecdh_clnt_cert = 1;
2202                                  */
2203                                 }
2204
2205                         if (s->session->sess_cert->peer_ecdh_tmp != NULL)
2206                                 {
2207                                 tkey = s->session->sess_cert->peer_ecdh_tmp;
2208                                 }
2209                         else
2210                                 {
2211                                 /* Get the Server Public Key from Cert */
2212                                 srvr_pub_pkey = X509_get_pubkey(s->session-> \
2213                                     sess_cert->peer_pkeys[SSL_PKEY_ECC].x509);
2214                                 if ((srvr_pub_pkey == NULL) ||
2215                                     (srvr_pub_pkey->type != EVP_PKEY_EC) ||
2216                                     (srvr_pub_pkey->pkey.ec == NULL))
2217                                         {
2218                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2219                                             ERR_R_INTERNAL_ERROR);
2220                                         goto err;
2221                                         }
2222
2223                                 tkey = srvr_pub_pkey->pkey.ec;
2224                                 }
2225
2226                         srvr_group   = EC_KEY_get0_group(tkey);
2227                         srvr_ecpoint = EC_KEY_get0_public_key(tkey);
2228
2229                         if ((srvr_group == NULL) || (srvr_ecpoint == NULL))
2230                                 {
2231                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2232                                     ERR_R_INTERNAL_ERROR);
2233                                 goto err;
2234                                 }
2235
2236                         if ((clnt_ecdh=EC_KEY_new()) == NULL) 
2237                                 {
2238                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2239                                 goto err;
2240                                 }
2241
2242                         if (!EC_KEY_set_group(clnt_ecdh, srvr_group))
2243                                 {
2244                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2245                                 goto err;
2246                                 }
2247                         if (ecdh_clnt_cert) 
2248                                 { 
2249                                 /* Reuse key info from our certificate
2250                                  * We only need our private key to perform
2251                                  * the ECDH computation.
2252                                  */
2253                                 const BIGNUM *priv_key;
2254                                 tkey = s->cert->key->privatekey->pkey.ec;
2255                                 priv_key = EC_KEY_get0_private_key(tkey);
2256                                 if (priv_key == NULL)
2257                                         {
2258                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2259                                         goto err;
2260                                         }
2261                                 if (!EC_KEY_set_private_key(clnt_ecdh, priv_key))
2262                                         {
2263                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_EC_LIB);
2264                                         goto err;
2265                                         }
2266                                 }
2267                         else 
2268                                 {
2269                                 /* Generate a new ECDH key pair */
2270                                 if (!(EC_KEY_generate_key(clnt_ecdh)))
2271                                         {
2272                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, ERR_R_ECDH_LIB);
2273                                         goto err;
2274                                         }
2275                                 }
2276
2277                         /* use the 'p' output buffer for the ECDH key, but
2278                          * make sure to clear it out afterwards
2279                          */
2280
2281                         field_size = EC_GROUP_get_degree(srvr_group);
2282                         if (field_size <= 0)
2283                                 {
2284                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2285                                        ERR_R_ECDH_LIB);
2286                                 goto err;
2287                                 }
2288                         n=ECDH_compute_key(p, (field_size+7)/8, srvr_ecpoint, clnt_ecdh, NULL);
2289                         if (n <= 0)
2290                                 {
2291                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, 
2292                                        ERR_R_ECDH_LIB);
2293                                 goto err;
2294                                 }
2295
2296                         /* generate master key from the result */
2297                         s->session->master_key_length = s->method->ssl3_enc \
2298                             -> generate_master_secret(s, 
2299                                 s->session->master_key,
2300                                 p, n);
2301
2302                         memset(p, 0, n); /* clean up */
2303
2304                         if (ecdh_clnt_cert) 
2305                                 {
2306                                 /* Send empty client key exch message */
2307                                 n = 0;
2308                                 }
2309                         else 
2310                                 {
2311                                 /* First check the size of encoding and
2312                                  * allocate memory accordingly.
2313                                  */
2314                                 encoded_pt_len = 
2315                                     EC_POINT_point2oct(srvr_group, 
2316                                         EC_KEY_get0_public_key(clnt_ecdh), 
2317                                         POINT_CONVERSION_UNCOMPRESSED, 
2318                                         NULL, 0, NULL);
2319
2320                                 encodedPoint = (unsigned char *) 
2321                                     OPENSSL_malloc(encoded_pt_len * 
2322                                         sizeof(unsigned char)); 
2323                                 bn_ctx = BN_CTX_new();
2324                                 if ((encodedPoint == NULL) || 
2325                                     (bn_ctx == NULL)) 
2326                                         {
2327                                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
2328                                         goto err;
2329                                         }
2330
2331                                 /* Encode the public key */
2332                                 n = EC_POINT_point2oct(srvr_group, 
2333                                     EC_KEY_get0_public_key(clnt_ecdh), 
2334                                     POINT_CONVERSION_UNCOMPRESSED, 
2335                                     encodedPoint, encoded_pt_len, bn_ctx);
2336
2337                                 *p = n; /* length of encoded point */
2338                                 /* Encoded point will be copied here */
2339                                 p += 1; 
2340                                 /* copy the point */
2341                                 memcpy((unsigned char *)p, encodedPoint, n);
2342                                 /* increment n to account for length field */
2343                                 n += 1; 
2344                                 }
2345
2346                         /* Free allocated memory */
2347                         BN_CTX_free(bn_ctx);
2348                         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2349                         if (clnt_ecdh != NULL) 
2350                                  EC_KEY_free(clnt_ecdh);
2351                         EVP_PKEY_free(srvr_pub_pkey);
2352                         }
2353 #endif /* !OPENSSL_NO_ECDH */
2354                 else
2355                         {
2356                         ssl3_send_alert(s, SSL3_AL_FATAL,
2357                             SSL_AD_HANDSHAKE_FAILURE);
2358                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
2359                             ERR_R_INTERNAL_ERROR);
2360                         goto err;
2361                         }
2362                 
2363                 *(d++)=SSL3_MT_CLIENT_KEY_EXCHANGE;
2364                 l2n3(n,d);
2365
2366                 s->state=SSL3_ST_CW_KEY_EXCH_B;
2367                 /* number of bytes to write */
2368                 s->init_num=n+4;
2369                 s->init_off=0;
2370                 }
2371
2372         /* SSL3_ST_CW_KEY_EXCH_B */
2373         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2374 err:
2375 #ifndef OPENSSL_NO_ECDH
2376         BN_CTX_free(bn_ctx);
2377         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2378         if (clnt_ecdh != NULL) 
2379                 EC_KEY_free(clnt_ecdh);
2380         EVP_PKEY_free(srvr_pub_pkey);
2381 #endif
2382         return(-1);
2383         }
2384
2385 int ssl3_send_client_verify(SSL *s)
2386         {
2387         unsigned char *p,*d;
2388         unsigned char data[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
2389         EVP_PKEY *pkey;
2390 #ifndef OPENSSL_NO_RSA
2391         unsigned u=0;
2392 #endif
2393         unsigned long n;
2394 #if !defined(OPENSSL_NO_DSA) || !defined(OPENSSL_NO_ECDSA)
2395         int j;
2396 #endif
2397
2398         if (s->state == SSL3_ST_CW_CERT_VRFY_A)
2399                 {
2400                 d=(unsigned char *)s->init_buf->data;
2401                 p= &(d[4]);
2402                 pkey=s->cert->key->privatekey;
2403
2404                 s->method->ssl3_enc->cert_verify_mac(s,&(s->s3->finish_dgst2),
2405                         &(data[MD5_DIGEST_LENGTH]));
2406
2407 #ifndef OPENSSL_NO_RSA
2408                 if (pkey->type == EVP_PKEY_RSA)
2409                         {
2410                         s->method->ssl3_enc->cert_verify_mac(s,
2411                                 &(s->s3->finish_dgst1),&(data[0]));
2412                         if (RSA_sign(NID_md5_sha1, data,
2413                                          MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH,
2414                                         &(p[2]), &u, pkey->pkey.rsa) <= 0 )
2415                                 {
2416                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_RSA_LIB);
2417                                 goto err;
2418                                 }
2419                         s2n(u,p);
2420                         n=u+2;
2421                         }
2422                 else
2423 #endif
2424 #ifndef OPENSSL_NO_DSA
2425                         if (pkey->type == EVP_PKEY_DSA)
2426                         {
2427                         if (!DSA_sign(pkey->save_type,
2428                                 &(data[MD5_DIGEST_LENGTH]),
2429                                 SHA_DIGEST_LENGTH,&(p[2]),
2430                                 (unsigned int *)&j,pkey->pkey.dsa))
2431                                 {
2432                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_DSA_LIB);
2433                                 goto err;
2434                                 }
2435                         s2n(j,p);
2436                         n=j+2;
2437                         }
2438                 else
2439 #endif
2440 #ifndef OPENSSL_NO_ECDSA
2441                         if (pkey->type == EVP_PKEY_EC)
2442                         {
2443                         if (!ECDSA_sign(pkey->save_type,
2444                                 &(data[MD5_DIGEST_LENGTH]),
2445                                 SHA_DIGEST_LENGTH,&(p[2]),
2446                                 (unsigned int *)&j,pkey->pkey.ec))
2447                                 {
2448                                 SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,
2449                                     ERR_R_ECDSA_LIB);
2450                                 goto err;
2451                                 }
2452                         s2n(j,p);
2453                         n=j+2;
2454                         }
2455                 else
2456 #endif
2457                         {
2458                         SSLerr(SSL_F_SSL3_SEND_CLIENT_VERIFY,ERR_R_INTERNAL_ERROR);
2459                         goto err;
2460                         }
2461                 *(d++)=SSL3_MT_CERTIFICATE_VERIFY;
2462                 l2n3(n,d);
2463
2464                 s->state=SSL3_ST_CW_CERT_VRFY_B;
2465                 s->init_num=(int)n+4;
2466                 s->init_off=0;
2467                 }
2468         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2469 err:
2470         return(-1);
2471         }
2472
2473 int ssl3_send_client_certificate(SSL *s)
2474         {
2475         X509 *x509=NULL;
2476         EVP_PKEY *pkey=NULL;
2477         int i;
2478         unsigned long l;
2479
2480         if (s->state == SSL3_ST_CW_CERT_A)
2481                 {
2482                 if ((s->cert == NULL) ||
2483                         (s->cert->key->x509 == NULL) ||
2484                         (s->cert->key->privatekey == NULL))
2485                         s->state=SSL3_ST_CW_CERT_B;
2486                 else
2487                         s->state=SSL3_ST_CW_CERT_C;
2488                 }
2489
2490         /* We need to get a client cert */
2491         if (s->state == SSL3_ST_CW_CERT_B)
2492                 {
2493                 /* If we get an error, we need to
2494                  * ssl->rwstate=SSL_X509_LOOKUP; return(-1);
2495                  * We then get retied later */
2496                 i=0;
2497                 i = ssl_do_client_cert_cb(s, &x509, &pkey);
2498                 if (i < 0)
2499                         {
2500                         s->rwstate=SSL_X509_LOOKUP;
2501                         return(-1);
2502                         }
2503                 s->rwstate=SSL_NOTHING;
2504                 if ((i == 1) && (pkey != NULL) && (x509 != NULL))
2505                         {
2506                         s->state=SSL3_ST_CW_CERT_B;
2507                         if (    !SSL_use_certificate(s,x509) ||
2508                                 !SSL_use_PrivateKey(s,pkey))
2509                                 i=0;
2510                         }
2511                 else if (i == 1)
2512                         {
2513                         i=0;
2514                         SSLerr(SSL_F_SSL3_SEND_CLIENT_CERTIFICATE,SSL_R_BAD_DATA_RETURNED_BY_CALLBACK);
2515                         }
2516
2517                 if (x509 != NULL) X509_free(x509);
2518                 if (pkey != NULL) EVP_PKEY_free(pkey);
2519                 if (i == 0)
2520                         {
2521                         if (s->version == SSL3_VERSION)
2522                                 {
2523                                 s->s3->tmp.cert_req=0;
2524                                 ssl3_send_alert(s,SSL3_AL_WARNING,SSL_AD_NO_CERTIFICATE);
2525                                 return(1);
2526                                 }
2527                         else
2528                                 {
2529                                 s->s3->tmp.cert_req=2;
2530                                 }
2531                         }
2532
2533                 /* Ok, we have a cert */
2534                 s->state=SSL3_ST_CW_CERT_C;
2535                 }
2536
2537         if (s->state == SSL3_ST_CW_CERT_C)
2538                 {
2539                 s->state=SSL3_ST_CW_CERT_D;
2540                 l=ssl3_output_cert_chain(s,
2541                         (s->s3->tmp.cert_req == 2)?NULL:s->cert->key->x509);
2542                 s->init_num=(int)l;
2543                 s->init_off=0;
2544                 }
2545         /* SSL3_ST_CW_CERT_D */
2546         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2547         }
2548
2549 #define has_bits(i,m)   (((i)&(m)) == (m))
2550
2551 int ssl3_check_cert_and_algorithm(SSL *s)
2552         {
2553         int i,idx;
2554         long algs;
2555         EVP_PKEY *pkey=NULL;
2556         SESS_CERT *sc;
2557 #ifndef OPENSSL_NO_RSA
2558         RSA *rsa;
2559 #endif
2560 #ifndef OPENSSL_NO_DH
2561         DH *dh;
2562 #endif
2563
2564         sc=s->session->sess_cert;
2565
2566         algs=s->s3->tmp.new_cipher->algorithms;
2567
2568         /* we don't have a certificate */
2569         if (algs & (SSL_aDH|SSL_aNULL|SSL_aKRB5))
2570                 return(1);
2571
2572         if (sc == NULL)
2573                 {
2574                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,ERR_R_INTERNAL_ERROR);
2575                 goto err;
2576                 }
2577
2578 #ifndef OPENSSL_NO_RSA
2579         rsa=s->session->sess_cert->peer_rsa_tmp;
2580 #endif
2581 #ifndef OPENSSL_NO_DH
2582         dh=s->session->sess_cert->peer_dh_tmp;
2583 #endif
2584
2585         /* This is the passed certificate */
2586
2587         idx=sc->peer_cert_type;
2588 #ifndef OPENSSL_NO_ECDH
2589         if (idx == SSL_PKEY_ECC)
2590                 {
2591                 if (check_srvr_ecc_cert_and_alg(sc->peer_pkeys[idx].x509,
2592                     s->s3->tmp.new_cipher) == 0) 
2593                         { /* check failed */
2594                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_BAD_ECC_CERT);
2595                         goto f_err;                     
2596                         }
2597                 else 
2598                         {
2599                         return 1;
2600                         }
2601                 }
2602 #endif
2603         pkey=X509_get_pubkey(sc->peer_pkeys[idx].x509);
2604         i=X509_certificate_type(sc->peer_pkeys[idx].x509,pkey);
2605         EVP_PKEY_free(pkey);
2606
2607         
2608         /* Check that we have a certificate if we require one */
2609         if ((algs & SSL_aRSA) && !has_bits(i,EVP_PK_RSA|EVP_PKT_SIGN))
2610                 {
2611                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_SIGNING_CERT);
2612                 goto f_err;
2613                 }
2614 #ifndef OPENSSL_NO_DSA
2615         else if ((algs & SSL_aDSS) && !has_bits(i,EVP_PK_DSA|EVP_PKT_SIGN))
2616                 {
2617                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DSA_SIGNING_CERT);
2618                 goto f_err;
2619                 }
2620 #endif
2621 #ifndef OPENSSL_NO_RSA
2622         if ((algs & SSL_kRSA) &&
2623                 !(has_bits(i,EVP_PK_RSA|EVP_PKT_ENC) || (rsa != NULL)))
2624                 {
2625                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_RSA_ENCRYPTING_CERT);
2626                 goto f_err;
2627                 }
2628 #endif
2629 #ifndef OPENSSL_NO_DH
2630         if ((algs & SSL_kEDH) &&
2631                 !(has_bits(i,EVP_PK_DH|EVP_PKT_EXCH) || (dh != NULL)))
2632                 {
2633                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_KEY);
2634                 goto f_err;
2635                 }
2636         else if ((algs & SSL_kDHr) && !has_bits(i,EVP_PK_DH|EVP_PKS_RSA))
2637                 {
2638                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_RSA_CERT);
2639                 goto f_err;
2640                 }
2641 #ifndef OPENSSL_NO_DSA
2642         else if ((algs & SSL_kDHd) && !has_bits(i,EVP_PK_DH|EVP_PKS_DSA))
2643                 {
2644                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_DH_DSA_CERT);
2645                 goto f_err;
2646                 }
2647 #endif
2648 #endif
2649
2650         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) && !has_bits(i,EVP_PKT_EXP))
2651                 {
2652 #ifndef OPENSSL_NO_RSA
2653                 if (algs & SSL_kRSA)
2654                         {
2655                         if (rsa == NULL
2656                             || RSA_size(rsa)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
2657                                 {
2658                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_RSA_KEY);
2659                                 goto f_err;
2660                                 }
2661                         }
2662                 else
2663 #endif
2664 #ifndef OPENSSL_NO_DH
2665                         if (algs & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2666                             {
2667                             if (dh == NULL
2668                                 || DH_size(dh)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher))
2669                                 {
2670                                 SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_MISSING_EXPORT_TMP_DH_KEY);
2671                                 goto f_err;
2672                                 }
2673                         }
2674                 else
2675 #endif
2676                         {
2677                         SSLerr(SSL_F_SSL3_CHECK_CERT_AND_ALGORITHM,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
2678                         goto f_err;
2679                         }
2680                 }
2681         return(1);
2682 f_err:
2683         ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
2684 err:
2685         return(0);
2686         }
2687
2688
2689 #ifndef OPENSSL_NO_ECDH
2690 /* This is the complement of nid2curve_id in s3_srvr.c. */
2691 static int curve_id2nid(int curve_id)
2692 {
2693         /* ECC curves from draft-ietf-tls-ecc-01.txt (Mar 15, 2001)
2694          * (no changes in draft-ietf-tls-ecc-03.txt [June 2003]) */
2695         static int nid_list[26] =
2696         {
2697                 0,
2698                 NID_sect163k1, /* sect163k1 (1) */
2699                 NID_sect163r1, /* sect163r1 (2) */
2700                 NID_sect163r2, /* sect163r2 (3) */
2701                 NID_sect193r1, /* sect193r1 (4) */ 
2702                 NID_sect193r2, /* sect193r2 (5) */ 
2703                 NID_sect233k1, /* sect233k1 (6) */
2704                 NID_sect233r1, /* sect233r1 (7) */ 
2705                 NID_sect239k1, /* sect239k1 (8) */ 
2706                 NID_sect283k1, /* sect283k1 (9) */
2707                 NID_sect283r1, /* sect283r1 (10) */ 
2708                 NID_sect409k1, /* sect409k1 (11) */ 
2709                 NID_sect409r1, /* sect409r1 (12) */
2710                 NID_sect571k1, /* sect571k1 (13) */ 
2711                 NID_sect571r1, /* sect571r1 (14) */ 
2712                 NID_secp160k1, /* secp160k1 (15) */
2713                 NID_secp160r1, /* secp160r1 (16) */ 
2714                 NID_secp160r2, /* secp160r2 (17) */ 
2715                 NID_secp192k1, /* secp192k1 (18) */
2716                 NID_X9_62_prime192v1, /* secp192r1 (19) */ 
2717                 NID_secp224k1, /* secp224k1 (20) */ 
2718                 NID_secp224r1, /* secp224r1 (21) */
2719                 NID_secp256k1, /* secp256k1 (22) */ 
2720                 NID_X9_62_prime256v1, /* secp256r1 (23) */ 
2721                 NID_secp384r1, /* secp384r1 (24) */
2722                 NID_secp521r1  /* secp521r1 (25) */     
2723         };
2724         
2725         if ((curve_id < 1) || (curve_id > 25)) return 0;
2726
2727         return nid_list[curve_id];
2728 }
2729 #endif
2730
2731 /* Check to see if handshake is full or resumed. Usually this is just a
2732  * case of checking to see if a cache hit has occurred. In the case of
2733  * session tickets we have to check the next message to be sure.
2734  */
2735
2736 #ifndef OPENSSL_NO_TLSEXT
2737 int ssl3_check_finished(SSL *s)
2738         {
2739         int ok;
2740         long n;
2741         /* If we have no ticket or session ID is non-zero length (a match of
2742          * a non-zero session length would never reach here) it cannot be a
2743          * resumed session.
2744          */
2745         if (!s->session->tlsext_tick || s->session->session_id_length)
2746                 return 1;
2747         /* this function is called when we really expect a Certificate
2748          * message, so permit appropriate message length */
2749         n=s->method->ssl_get_message(s,
2750                 SSL3_ST_CR_CERT_A,
2751                 SSL3_ST_CR_CERT_B,
2752                 -1,
2753                 s->max_cert_list,
2754                 &ok);
2755         if (!ok) return((int)n);
2756         s->s3->tmp.reuse_message = 1;
2757         if ((s->s3->tmp.message_type == SSL3_MT_FINISHED)
2758                 || (s->s3->tmp.message_type == SSL3_MT_NEWSESSION_TICKET))
2759                 return 2;
2760
2761         return 1;
2762         }
2763 #endif
2764
2765 int ssl_do_client_cert_cb(SSL *s, X509 **px509, EVP_PKEY **ppkey)
2766         {
2767         int i = 0;
2768 #ifndef OPENSSL_NO_ENGINE
2769         if (s->ctx->client_cert_engine)
2770                 {
2771                 i = ENGINE_load_ssl_client_cert(s->ctx->client_cert_engine, s,
2772                                                 SSL_get_client_CA_list(s),
2773                                                 px509, ppkey, NULL, NULL, NULL);
2774                 if (i != 0)
2775                         return i;
2776                 }
2777 #endif
2778         if (s->ctx->client_cert_cb)
2779                 i = s->ctx->client_cert_cb(s,px509,ppkey);
2780         return i;
2781         }