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