It seems like OpenUnix's ld uses LD_LIBRARY_PATH to search for
[openssl.git] / ssl / s3_srvr.c
1 /* ssl/s3_srvr.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 #define REUSE_CIPHER_BUG
126 #define NETSCAPE_HANG_BUG
127
128 #include <stdio.h>
129 #include "ssl_locl.h"
130 #include "kssl_lcl.h"
131 #include <openssl/buffer.h>
132 #include <openssl/rand.h>
133 #include <openssl/objects.h>
134 #include <openssl/evp.h>
135 #include <openssl/x509.h>
136 #include <openssl/krb5_asn.h>
137 #include <openssl/md5.h>
138 #include "cryptlib.h"
139
140 static SSL_METHOD *ssl3_get_server_method(int ver);
141 static int ssl3_get_client_hello(SSL *s);
142 static int ssl3_check_client_hello(SSL *s);
143 static int ssl3_send_server_hello(SSL *s);
144 static int ssl3_send_server_key_exchange(SSL *s);
145 static int ssl3_send_certificate_request(SSL *s);
146 static int ssl3_send_server_done(SSL *s);
147 static int ssl3_get_client_key_exchange(SSL *s);
148 static int ssl3_get_client_certificate(SSL *s);
149 static int ssl3_get_cert_verify(SSL *s);
150 static int ssl3_send_hello_request(SSL *s);
151
152 #ifndef OPENSSL_NO_ECDH
153 static int nid2curve_id(int nid);
154 #endif
155
156 static SSL_METHOD *ssl3_get_server_method(int ver)
157         {
158         if (ver == SSL3_VERSION)
159                 return(SSLv3_server_method());
160         else
161                 return(NULL);
162         }
163
164 SSL_METHOD *SSLv3_server_method(void)
165         {
166         static int init=1;
167         static SSL_METHOD SSLv3_server_data;
168
169         if (init)
170                 {
171                 CRYPTO_w_lock(CRYPTO_LOCK_SSL_METHOD);
172
173                 if (init)
174                         {
175                         memcpy((char *)&SSLv3_server_data,(char *)sslv3_base_method(),
176                                 sizeof(SSL_METHOD));
177                         SSLv3_server_data.ssl_accept=ssl3_accept;
178                         SSLv3_server_data.get_ssl_method=ssl3_get_server_method;
179                         init=0;
180                         }
181                         
182                 CRYPTO_w_unlock(CRYPTO_LOCK_SSL_METHOD);
183                 }
184         return(&SSLv3_server_data);
185         }
186
187 int ssl3_accept(SSL *s)
188         {
189         BUF_MEM *buf;
190         unsigned long l,Time=time(NULL);
191         void (*cb)(const SSL *ssl,int type,int val)=NULL;
192         long num1;
193         int ret= -1;
194         int new_state,state,skip=0;
195
196         RAND_add(&Time,sizeof(Time),0);
197         ERR_clear_error();
198         clear_sys_error();
199
200         if (s->info_callback != NULL)
201                 cb=s->info_callback;
202         else if (s->ctx->info_callback != NULL)
203                 cb=s->ctx->info_callback;
204
205         /* init things to blank */
206         s->in_handshake++;
207         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
208
209         if (s->cert == NULL)
210                 {
211                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
212                 return(-1);
213                 }
214
215         for (;;)
216                 {
217                 state=s->state;
218
219                 switch (s->state)
220                         {
221                 case SSL_ST_RENEGOTIATE:
222                         s->new_session=1;
223                         /* s->state=SSL_ST_ACCEPT; */
224
225                 case SSL_ST_BEFORE:
226                 case SSL_ST_ACCEPT:
227                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
228                 case SSL_ST_OK|SSL_ST_ACCEPT:
229
230                         s->server=1;
231                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
232
233                         if ((s->version>>8) != 3)
234                                 {
235                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
236                                 return -1;
237                                 }
238                         s->type=SSL_ST_ACCEPT;
239
240                         if (s->init_buf == NULL)
241                                 {
242                                 if ((buf=BUF_MEM_new()) == NULL)
243                                         {
244                                         ret= -1;
245                                         goto end;
246                                         }
247                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
248                                         {
249                                         ret= -1;
250                                         goto end;
251                                         }
252                                 s->init_buf=buf;
253                                 }
254
255                         if (!ssl3_setup_buffers(s))
256                                 {
257                                 ret= -1;
258                                 goto end;
259                                 }
260
261                         s->init_num=0;
262
263                         if (s->state != SSL_ST_RENEGOTIATE)
264                                 {
265                                 /* Ok, we now need to push on a buffering BIO so that
266                                  * the output is sent in a way that TCP likes :-)
267                                  */
268                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
269                                 
270                                 ssl3_init_finished_mac(s);
271                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
272                                 s->ctx->stats.sess_accept++;
273                                 }
274                         else
275                                 {
276                                 /* s->state == SSL_ST_RENEGOTIATE,
277                                  * we will just send a HelloRequest */
278                                 s->ctx->stats.sess_accept_renegotiate++;
279                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
280                                 }
281                         break;
282
283                 case SSL3_ST_SW_HELLO_REQ_A:
284                 case SSL3_ST_SW_HELLO_REQ_B:
285
286                         s->shutdown=0;
287                         ret=ssl3_send_hello_request(s);
288                         if (ret <= 0) goto end;
289                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
290                         s->state=SSL3_ST_SW_FLUSH;
291                         s->init_num=0;
292
293                         ssl3_init_finished_mac(s);
294                         break;
295
296                 case SSL3_ST_SW_HELLO_REQ_C:
297                         s->state=SSL_ST_OK;
298                         break;
299
300                 case SSL3_ST_SR_CLNT_HELLO_A:
301                 case SSL3_ST_SR_CLNT_HELLO_B:
302                 case SSL3_ST_SR_CLNT_HELLO_C:
303
304                         s->shutdown=0;
305                         ret=ssl3_get_client_hello(s);
306                         if (ret <= 0) goto end;
307                         s->new_session = 2;
308                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
309                         s->init_num=0;
310                         break;
311
312                 case SSL3_ST_SW_SRVR_HELLO_A:
313                 case SSL3_ST_SW_SRVR_HELLO_B:
314                         ret=ssl3_send_server_hello(s);
315                         if (ret <= 0) goto end;
316
317                         if (s->hit)
318                                 s->state=SSL3_ST_SW_CHANGE_A;
319                         else
320                                 s->state=SSL3_ST_SW_CERT_A;
321                         s->init_num=0;
322                         break;
323
324                 case SSL3_ST_SW_CERT_A:
325                 case SSL3_ST_SW_CERT_B:
326                         /* Check if it is anon DH or anon ECDH */
327                         if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
328                                 {
329                                 ret=ssl3_send_server_certificate(s);
330                                 if (ret <= 0) goto end;
331                                 }
332                         else
333                                 skip=1;
334                         s->state=SSL3_ST_SW_KEY_EXCH_A;
335                         s->init_num=0;
336                         break;
337
338                 case SSL3_ST_SW_KEY_EXCH_A:
339                 case SSL3_ST_SW_KEY_EXCH_B:
340                         l=s->s3->tmp.new_cipher->algorithms;
341
342                         /* clear this, it may get reset by
343                          * send_server_key_exchange */
344                         if ((s->options & SSL_OP_EPHEMERAL_RSA)
345 #ifndef OPENSSL_NO_KRB5
346                                 && !(l & SSL_KRB5)
347 #endif /* OPENSSL_NO_KRB5 */
348                                 )
349                                 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
350                                  * even when forbidden by protocol specs
351                                  * (handshake may fail as clients are not required to
352                                  * be able to handle this) */
353                                 s->s3->tmp.use_rsa_tmp=1;
354                         else
355                                 s->s3->tmp.use_rsa_tmp=0;
356
357
358                         /* only send if a DH key exchange, fortezza or
359                          * RSA but we have a sign only certificate
360                          *
361                          * For ECC ciphersuites, we send a serverKeyExchange
362                          * message only if the cipher suite is either
363                          * ECDH-anon or ECDHE. In other cases, the
364                          * server certificate contains the server's 
365                          * public key for key exchange.
366                          */
367                         if (s->s3->tmp.use_rsa_tmp
368                             || (l & SSL_kECDHE)
369                             || (l & (SSL_DH|SSL_kFZA))
370                             || ((l & SSL_kRSA)
371                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
372                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
373                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
374                                         )
375                                     )
376                                 )
377                             )
378                                 {
379                                 ret=ssl3_send_server_key_exchange(s);
380                                 if (ret <= 0) goto end;
381                                 }
382                         else
383                                 skip=1;
384
385                         s->state=SSL3_ST_SW_CERT_REQ_A;
386                         s->init_num=0;
387                         break;
388
389                 case SSL3_ST_SW_CERT_REQ_A:
390                 case SSL3_ST_SW_CERT_REQ_B:
391                         if (/* don't request cert unless asked for it: */
392                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
393                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
394                                  * don't request cert during re-negotiation: */
395                                 ((s->session->peer != NULL) &&
396                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
397                                 /* never request cert in anonymous ciphersuites
398                                  * (see section "Certificate request" in SSL 3 drafts
399                                  * and in RFC 2246): */
400                                 ((s->s3->tmp.new_cipher->algorithms & SSL_aNULL) &&
401                                  /* ... except when the application insists on verification
402                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
403                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
404                                  /* never request cert in Kerberos ciphersuites */
405                                 (s->s3->tmp.new_cipher->algorithms & SSL_aKRB5))
406                                 {
407                                 /* no cert request */
408                                 skip=1;
409                                 s->s3->tmp.cert_request=0;
410                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
411                                 }
412                         else
413                                 {
414                                 s->s3->tmp.cert_request=1;
415                                 ret=ssl3_send_certificate_request(s);
416                                 if (ret <= 0) goto end;
417 #ifndef NETSCAPE_HANG_BUG
418                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
419 #else
420                                 s->state=SSL3_ST_SW_FLUSH;
421                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
422 #endif
423                                 s->init_num=0;
424                                 }
425                         break;
426
427                 case SSL3_ST_SW_SRVR_DONE_A:
428                 case SSL3_ST_SW_SRVR_DONE_B:
429                         ret=ssl3_send_server_done(s);
430                         if (ret <= 0) goto end;
431                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
432                         s->state=SSL3_ST_SW_FLUSH;
433                         s->init_num=0;
434                         break;
435                 
436                 case SSL3_ST_SW_FLUSH:
437                         /* number of bytes to be flushed */
438                         num1=BIO_ctrl(s->wbio,BIO_CTRL_INFO,0,NULL);
439                         if (num1 > 0)
440                                 {
441                                 s->rwstate=SSL_WRITING;
442                                 num1=BIO_flush(s->wbio);
443                                 if (num1 <= 0) { ret= -1; goto end; }
444                                 s->rwstate=SSL_NOTHING;
445                                 }
446
447                         s->state=s->s3->tmp.next_state;
448                         break;
449
450                 case SSL3_ST_SR_CERT_A:
451                 case SSL3_ST_SR_CERT_B:
452                         /* Check for second client hello (MS SGC) */
453                         ret = ssl3_check_client_hello(s);
454                         if (ret <= 0)
455                                 goto end;
456                         if (ret == 2)
457                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
458                         else {
459                                 /* could be sent for a DH cert, even if we
460                                  * have not asked for it :-) */
461                                 ret=ssl3_get_client_certificate(s);
462                                 if (ret <= 0) goto end;
463                                 s->init_num=0;
464                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
465                         }
466                         break;
467
468                 case SSL3_ST_SR_KEY_EXCH_A:
469                 case SSL3_ST_SR_KEY_EXCH_B:
470                         ret=ssl3_get_client_key_exchange(s);
471                         if (ret <= 0) 
472                                 goto end;
473                         if (ret == 2)
474                                 {
475                                 /* For the ECDH ciphersuites when
476                                  * the client sends its ECDH pub key in
477                                  * a certificate, the CertificateVerify
478                                  * message is not sent.
479                                  */
480                                 s->state=SSL3_ST_SR_FINISHED_A;
481                                 s->init_num = 0;
482                                 }
483                         else   
484                                 {
485                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
486                                 s->init_num=0;
487
488                                 /* We need to get hashes here so if there is
489                                  * a client cert, it can be verified
490                                  */ 
491                                 s->method->ssl3_enc->cert_verify_mac(s,
492                                     &(s->s3->finish_dgst1),
493                                     &(s->s3->tmp.cert_verify_md[0]));
494                                 s->method->ssl3_enc->cert_verify_mac(s,
495                                     &(s->s3->finish_dgst2),
496                                     &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]));
497                                 }
498                         break;
499
500                 case SSL3_ST_SR_CERT_VRFY_A:
501                 case SSL3_ST_SR_CERT_VRFY_B:
502
503                         /* we should decide if we expected this one */
504                         ret=ssl3_get_cert_verify(s);
505                         if (ret <= 0) goto end;
506
507                         s->state=SSL3_ST_SR_FINISHED_A;
508                         s->init_num=0;
509                         break;
510
511                 case SSL3_ST_SR_FINISHED_A:
512                 case SSL3_ST_SR_FINISHED_B:
513                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
514                                 SSL3_ST_SR_FINISHED_B);
515                         if (ret <= 0) goto end;
516                         if (s->hit)
517                                 s->state=SSL_ST_OK;
518                         else
519                                 s->state=SSL3_ST_SW_CHANGE_A;
520                         s->init_num=0;
521                         break;
522
523                 case SSL3_ST_SW_CHANGE_A:
524                 case SSL3_ST_SW_CHANGE_B:
525
526                         s->session->cipher=s->s3->tmp.new_cipher;
527                         if (!s->method->ssl3_enc->setup_key_block(s))
528                                 { ret= -1; goto end; }
529
530                         ret=ssl3_send_change_cipher_spec(s,
531                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
532
533                         if (ret <= 0) goto end;
534                         s->state=SSL3_ST_SW_FINISHED_A;
535                         s->init_num=0;
536
537                         if (!s->method->ssl3_enc->change_cipher_state(s,
538                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
539                                 {
540                                 ret= -1;
541                                 goto end;
542                                 }
543
544                         break;
545
546                 case SSL3_ST_SW_FINISHED_A:
547                 case SSL3_ST_SW_FINISHED_B:
548                         ret=ssl3_send_finished(s,
549                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
550                                 s->method->ssl3_enc->server_finished_label,
551                                 s->method->ssl3_enc->server_finished_label_len);
552                         if (ret <= 0) goto end;
553                         s->state=SSL3_ST_SW_FLUSH;
554                         if (s->hit)
555                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
556                         else
557                                 s->s3->tmp.next_state=SSL_ST_OK;
558                         s->init_num=0;
559                         break;
560
561                 case SSL_ST_OK:
562                         /* clean a few things up */
563                         ssl3_cleanup_key_block(s);
564
565                         BUF_MEM_free(s->init_buf);
566                         s->init_buf=NULL;
567
568                         /* remove buffering on output */
569                         ssl_free_wbio_buffer(s);
570
571                         s->init_num=0;
572
573                         if (s->new_session == 2) /* skipped if we just sent a HelloRequest */
574                                 {
575                                 /* actually not necessarily a 'new' session unless
576                                  * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is set */
577                                 
578                                 s->new_session=0;
579                                 
580                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
581                                 
582                                 s->ctx->stats.sess_accept_good++;
583                                 /* s->server=1; */
584                                 s->handshake_func=ssl3_accept;
585
586                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
587                                 }
588                         
589                         ret = 1;
590                         goto end;
591                         /* break; */
592
593                 default:
594                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
595                         ret= -1;
596                         goto end;
597                         /* break; */
598                         }
599                 
600                 if (!s->s3->tmp.reuse_message && !skip)
601                         {
602                         if (s->debug)
603                                 {
604                                 if ((ret=BIO_flush(s->wbio)) <= 0)
605                                         goto end;
606                                 }
607
608
609                         if ((cb != NULL) && (s->state != state))
610                                 {
611                                 new_state=s->state;
612                                 s->state=state;
613                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
614                                 s->state=new_state;
615                                 }
616                         }
617                 skip=0;
618                 }
619 end:
620         /* BIO_flush(s->wbio); */
621
622         s->in_handshake--;
623         if (cb != NULL)
624                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
625         return(ret);
626         }
627
628 static int ssl3_send_hello_request(SSL *s)
629         {
630         unsigned char *p;
631
632         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
633                 {
634                 p=(unsigned char *)s->init_buf->data;
635                 *(p++)=SSL3_MT_HELLO_REQUEST;
636                 *(p++)=0;
637                 *(p++)=0;
638                 *(p++)=0;
639
640                 s->state=SSL3_ST_SW_HELLO_REQ_B;
641                 /* number of bytes to write */
642                 s->init_num=4;
643                 s->init_off=0;
644                 }
645
646         /* SSL3_ST_SW_HELLO_REQ_B */
647         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
648         }
649
650 static int ssl3_check_client_hello(SSL *s)
651         {
652         int ok;
653         long n;
654
655         /* this function is called when we really expect a Certificate message,
656          * so permit appropriate message length */
657         n=ssl3_get_message(s,
658                 SSL3_ST_SR_CERT_A,
659                 SSL3_ST_SR_CERT_B,
660                 -1,
661                 s->max_cert_list,
662                 &ok);
663         if (!ok) return((int)n);
664         s->s3->tmp.reuse_message = 1;
665         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
666                 {
667                 /* Throw away what we have done so far in the current handshake,
668                  * which will now be aborted. (A full SSL_clear would be too much.)
669                  * I hope that tmp.dh is the only thing that may need to be cleared
670                  * when a handshake is not completed ... */
671 #ifndef OPENSSL_NO_DH
672                 if (s->s3->tmp.dh != NULL)
673                         {
674                         DH_free(s->s3->tmp.dh);
675                         s->s3->tmp.dh = NULL;
676                         }
677 #endif
678                 return 2;
679                 }
680         return 1;
681 }
682
683 static int ssl3_get_client_hello(SSL *s)
684         {
685         int i,j,ok,al,ret= -1;
686         long n;
687         unsigned long id;
688         unsigned char *p,*d,*q;
689         SSL_CIPHER *c;
690         SSL_COMP *comp=NULL;
691         STACK_OF(SSL_CIPHER) *ciphers=NULL;
692
693         /* We do this so that we will respond with our native type.
694          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
695          * This down switching should be handled by a different method.
696          * If we are SSLv3, we will respond with SSLv3, even if prompted with
697          * TLSv1.
698          */
699         if (s->state == SSL3_ST_SR_CLNT_HELLO_A)
700                 {
701                 s->first_packet=1;
702                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
703                 }
704         n=ssl3_get_message(s,
705                 SSL3_ST_SR_CLNT_HELLO_B,
706                 SSL3_ST_SR_CLNT_HELLO_C,
707                 SSL3_MT_CLIENT_HELLO,
708                 SSL3_RT_MAX_PLAIN_LENGTH,
709                 &ok);
710
711         if (!ok) return((int)n);
712         d=p=(unsigned char *)s->init_msg;
713
714         /* use version from inside client hello, not from record header
715          * (may differ: see RFC 2246, Appendix E, second paragraph) */
716         s->client_version=(((int)p[0])<<8)|(int)p[1];
717         p+=2;
718
719         if (s->client_version < s->version)
720                 {
721                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
722                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR) 
723                         {
724                         /* similar to ssl3_get_record, send alert using remote version number */
725                         s->version = s->client_version;
726                         }
727                 al = SSL_AD_PROTOCOL_VERSION;
728                 goto f_err;
729                 }
730
731         /* load the client random */
732         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
733         p+=SSL3_RANDOM_SIZE;
734
735         /* get the session-id */
736         j= *(p++);
737
738         s->hit=0;
739         /* Versions before 0.9.7 always allow session reuse during renegotiation
740          * (i.e. when s->new_session is true), option
741          * SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION is new with 0.9.7.
742          * Maybe this optional behaviour should always have been the default,
743          * but we cannot safely change the default behaviour (or new applications
744          * might be written that become totally unsecure when compiled with
745          * an earlier library version)
746          */
747         if (j == 0 || (s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
748                 {
749                 if (!ssl_get_new_session(s,1))
750                         goto err;
751                 }
752         else
753                 {
754                 i=ssl_get_prev_session(s,p,j);
755                 if (i == 1)
756                         { /* previous session */
757                         s->hit=1;
758                         }
759                 else if (i == -1)
760                         goto err;
761                 else /* i == 0 */
762                         {
763                         if (!ssl_get_new_session(s,1))
764                                 goto err;
765                         }
766                 }
767
768         p+=j;
769         n2s(p,i);
770         if ((i == 0) && (j != 0))
771                 {
772                 /* we need a cipher if we are not resuming a session */
773                 al=SSL_AD_ILLEGAL_PARAMETER;
774                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
775                 goto f_err;
776                 }
777         if ((p+i) >= (d+n))
778                 {
779                 /* not enough data */
780                 al=SSL_AD_DECODE_ERROR;
781                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
782                 goto f_err;
783                 }
784         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
785                 == NULL))
786                 {
787                 goto err;
788                 }
789         p+=i;
790
791         /* If it is a hit, check that the cipher is in the list */
792         if ((s->hit) && (i > 0))
793                 {
794                 j=0;
795                 id=s->session->cipher->id;
796
797 #ifdef CIPHER_DEBUG
798                 printf("client sent %d ciphers\n",sk_num(ciphers));
799 #endif
800                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
801                         {
802                         c=sk_SSL_CIPHER_value(ciphers,i);
803 #ifdef CIPHER_DEBUG
804                         printf("client [%2d of %2d]:%s\n",
805                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
806 #endif
807                         if (c->id == id)
808                                 {
809                                 j=1;
810                                 break;
811                                 }
812                         }
813                 if (j == 0)
814                         {
815                         if ((s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
816                                 {
817                                 /* Very bad for multi-threading.... */
818                                 s->session->cipher=sk_SSL_CIPHER_value(ciphers,
819                                                                        0);
820                                 }
821                         else
822                                 {
823                                 /* we need to have the cipher in the cipher
824                                  * list if we are asked to reuse it */
825                                 al=SSL_AD_ILLEGAL_PARAMETER;
826                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
827                                 goto f_err;
828                                 }
829                         }
830                 }
831
832         /* compression */
833         i= *(p++);
834         if ((p+i) > (d+n))
835                 {
836                 /* not enough data */
837                 al=SSL_AD_DECODE_ERROR;
838                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
839                 goto f_err;
840                 }
841         q=p;
842         for (j=0; j<i; j++)
843                 {
844                 if (p[j] == 0) break;
845                 }
846
847         p+=i;
848         if (j >= i)
849                 {
850                 /* no compress */
851                 al=SSL_AD_DECODE_ERROR;
852                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
853                 goto f_err;
854                 }
855
856         /* Worst case, we will use the NULL compression, but if we have other
857          * options, we will now look for them.  We have i-1 compression
858          * algorithms from the client, starting at q. */
859         s->s3->tmp.new_compression=NULL;
860         if (s->ctx->comp_methods != NULL)
861                 { /* See if we have a match */
862                 int m,nn,o,v,done=0;
863
864                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
865                 for (m=0; m<nn; m++)
866                         {
867                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
868                         v=comp->id;
869                         for (o=0; o<i; o++)
870                                 {
871                                 if (v == q[o])
872                                         {
873                                         done=1;
874                                         break;
875                                         }
876                                 }
877                         if (done) break;
878                         }
879                 if (done)
880                         s->s3->tmp.new_compression=comp;
881                 else
882                         comp=NULL;
883                 }
884
885         /* TLS does not mind if there is extra stuff */
886         if (s->version == SSL3_VERSION)
887                 {
888                 if (p < (d+n))
889                         {
890                         /* wrong number of bytes,
891                          * there could be more to follow */
892                         al=SSL_AD_DECODE_ERROR;
893                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
894                         goto f_err;
895                         }
896                 }
897
898         /* Given s->session->ciphers and SSL_get_ciphers, we must
899          * pick a cipher */
900
901         if (!s->hit)
902                 {
903                 s->session->compress_meth=(comp == NULL)?0:comp->id;
904                 if (s->session->ciphers != NULL)
905                         sk_SSL_CIPHER_free(s->session->ciphers);
906                 s->session->ciphers=ciphers;
907                 if (ciphers == NULL)
908                         {
909                         al=SSL_AD_ILLEGAL_PARAMETER;
910                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
911                         goto f_err;
912                         }
913                 ciphers=NULL;
914                 c=ssl3_choose_cipher(s,s->session->ciphers,
915                                      SSL_get_ciphers(s));
916
917                 if (c == NULL)
918                         {
919                         al=SSL_AD_HANDSHAKE_FAILURE;
920                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
921                         goto f_err;
922                         }
923                 s->s3->tmp.new_cipher=c;
924                 }
925         else
926                 {
927                 /* Session-id reuse */
928 #ifdef REUSE_CIPHER_BUG
929                 STACK_OF(SSL_CIPHER) *sk;
930                 SSL_CIPHER *nc=NULL;
931                 SSL_CIPHER *ec=NULL;
932
933                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
934                         {
935                         sk=s->session->ciphers;
936                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
937                                 {
938                                 c=sk_SSL_CIPHER_value(sk,i);
939                                 if (c->algorithms & SSL_eNULL)
940                                         nc=c;
941                                 if (SSL_C_IS_EXPORT(c))
942                                         ec=c;
943                                 }
944                         if (nc != NULL)
945                                 s->s3->tmp.new_cipher=nc;
946                         else if (ec != NULL)
947                                 s->s3->tmp.new_cipher=ec;
948                         else
949                                 s->s3->tmp.new_cipher=s->session->cipher;
950                         }
951                 else
952 #endif
953                 s->s3->tmp.new_cipher=s->session->cipher;
954                 }
955         
956         /* we now have the following setup. 
957          * client_random
958          * cipher_list          - our prefered list of ciphers
959          * ciphers              - the clients prefered list of ciphers
960          * compression          - basically ignored right now
961          * ssl version is set   - sslv3
962          * s->session           - The ssl session has been setup.
963          * s->hit               - session reuse flag
964          * s->tmp.new_cipher    - the new cipher to use.
965          */
966
967         ret=1;
968         if (0)
969                 {
970 f_err:
971                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
972                 }
973 err:
974         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
975         return(ret);
976         }
977
978 static int ssl3_send_server_hello(SSL *s)
979         {
980         unsigned char *buf;
981         unsigned char *p,*d;
982         int i,sl;
983         unsigned long l,Time;
984
985         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
986                 {
987                 buf=(unsigned char *)s->init_buf->data;
988                 p=s->s3->server_random;
989                 Time=time(NULL);                        /* Time */
990                 l2n(Time,p);
991                 RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-sizeof(Time));
992                 /* Do the message type and length last */
993                 d=p= &(buf[4]);
994
995                 *(p++)=s->version>>8;
996                 *(p++)=s->version&0xff;
997
998                 /* Random stuff */
999                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1000                 p+=SSL3_RANDOM_SIZE;
1001
1002                 /* now in theory we have 3 options to sending back the
1003                  * session id.  If it is a re-use, we send back the
1004                  * old session-id, if it is a new session, we send
1005                  * back the new session-id or we send back a 0 length
1006                  * session-id if we want it to be single use.
1007                  * Currently I will not implement the '0' length session-id
1008                  * 12-Jan-98 - I'll now support the '0' length stuff.
1009                  */
1010                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER))
1011                         s->session->session_id_length=0;
1012
1013                 sl=s->session->session_id_length;
1014                 if (sl > sizeof s->session->session_id)
1015                         {
1016                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1017                         return -1;
1018                         }
1019                 *(p++)=sl;
1020                 memcpy(p,s->session->session_id,sl);
1021                 p+=sl;
1022
1023                 /* put the cipher */
1024                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1025                 p+=i;
1026
1027                 /* put the compression method */
1028                 if (s->s3->tmp.new_compression == NULL)
1029                         *(p++)=0;
1030                 else
1031                         *(p++)=s->s3->tmp.new_compression->id;
1032
1033                 /* do the header */
1034                 l=(p-d);
1035                 d=buf;
1036                 *(d++)=SSL3_MT_SERVER_HELLO;
1037                 l2n3(l,d);
1038
1039                 s->state=SSL3_ST_CW_CLNT_HELLO_B;
1040                 /* number of bytes to write */
1041                 s->init_num=p-buf;
1042                 s->init_off=0;
1043                 }
1044
1045         /* SSL3_ST_CW_CLNT_HELLO_B */
1046         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1047         }
1048
1049 static int ssl3_send_server_done(SSL *s)
1050         {
1051         unsigned char *p;
1052
1053         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1054                 {
1055                 p=(unsigned char *)s->init_buf->data;
1056
1057                 /* do the header */
1058                 *(p++)=SSL3_MT_SERVER_DONE;
1059                 *(p++)=0;
1060                 *(p++)=0;
1061                 *(p++)=0;
1062
1063                 s->state=SSL3_ST_SW_SRVR_DONE_B;
1064                 /* number of bytes to write */
1065                 s->init_num=4;
1066                 s->init_off=0;
1067                 }
1068
1069         /* SSL3_ST_CW_CLNT_HELLO_B */
1070         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1071         }
1072
1073 static int ssl3_send_server_key_exchange(SSL *s)
1074         {
1075 #ifndef OPENSSL_NO_RSA
1076         unsigned char *q;
1077         int j,num;
1078         RSA *rsa;
1079         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1080         unsigned int u;
1081 #endif
1082 #ifndef OPENSSL_NO_DH
1083         DH *dh=NULL,*dhp;
1084 #endif
1085 #ifndef OPENSSL_NO_ECDH
1086         EC_KEY *ecdh=NULL, *ecdhp;
1087         unsigned char *encodedPoint = NULL;
1088         int encodedlen = 0;
1089         int curve_id = 0;
1090         BN_CTX *bn_ctx = NULL; 
1091 #endif
1092         EVP_PKEY *pkey;
1093         unsigned char *p,*d;
1094         int al,i;
1095         unsigned long type;
1096         int n;
1097         CERT *cert;
1098         BIGNUM *r[4];
1099         int nr[4],kn;
1100         BUF_MEM *buf;
1101         EVP_MD_CTX md_ctx;
1102
1103         EVP_MD_CTX_init(&md_ctx);
1104         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1105                 {
1106                 type=s->s3->tmp.new_cipher->algorithms & SSL_MKEY_MASK;
1107                 cert=s->cert;
1108
1109                 buf=s->init_buf;
1110
1111                 r[0]=r[1]=r[2]=r[3]=NULL;
1112                 n=0;
1113 #ifndef OPENSSL_NO_RSA
1114                 if (type & SSL_kRSA)
1115                         {
1116                         rsa=cert->rsa_tmp;
1117                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1118                                 {
1119                                 rsa=s->cert->rsa_tmp_cb(s,
1120                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1121                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1122                                 if(rsa == NULL)
1123                                 {
1124                                         al=SSL_AD_HANDSHAKE_FAILURE;
1125                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1126                                         goto f_err;
1127                                 }
1128                                 RSA_up_ref(rsa);
1129                                 cert->rsa_tmp=rsa;
1130                                 }
1131                         if (rsa == NULL)
1132                                 {
1133                                 al=SSL_AD_HANDSHAKE_FAILURE;
1134                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1135                                 goto f_err;
1136                                 }
1137                         r[0]=rsa->n;
1138                         r[1]=rsa->e;
1139                         s->s3->tmp.use_rsa_tmp=1;
1140                         }
1141                 else
1142 #endif
1143 #ifndef OPENSSL_NO_DH
1144                         if (type & SSL_kEDH)
1145                         {
1146                         dhp=cert->dh_tmp;
1147                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1148                                 dhp=s->cert->dh_tmp_cb(s,
1149                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1150                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1151                         if (dhp == NULL)
1152                                 {
1153                                 al=SSL_AD_HANDSHAKE_FAILURE;
1154                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1155                                 goto f_err;
1156                                 }
1157
1158                         if (s->s3->tmp.dh != NULL)
1159                                 {
1160                                 DH_free(dh);
1161                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1162                                 goto err;
1163                                 }
1164
1165                         if ((dh=DHparams_dup(dhp)) == NULL)
1166                                 {
1167                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1168                                 goto err;
1169                                 }
1170
1171                         s->s3->tmp.dh=dh;
1172                         if ((dhp->pub_key == NULL ||
1173                              dhp->priv_key == NULL ||
1174                              (s->options & SSL_OP_SINGLE_DH_USE)))
1175                                 {
1176                                 if(!DH_generate_key(dh))
1177                                     {
1178                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1179                                            ERR_R_DH_LIB);
1180                                     goto err;
1181                                     }
1182                                 }
1183                         else
1184                                 {
1185                                 dh->pub_key=BN_dup(dhp->pub_key);
1186                                 dh->priv_key=BN_dup(dhp->priv_key);
1187                                 if ((dh->pub_key == NULL) ||
1188                                         (dh->priv_key == NULL))
1189                                         {
1190                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1191                                         goto err;
1192                                         }
1193                                 }
1194                         r[0]=dh->p;
1195                         r[1]=dh->g;
1196                         r[2]=dh->pub_key;
1197                         }
1198                 else 
1199 #endif
1200 #ifndef OPENSSL_NO_ECDH
1201                         if (type & SSL_kECDHE)
1202                         {
1203                         ecdhp=cert->ecdh_tmp;
1204                         if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
1205                                 {
1206                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1207                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1208                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1209                                 }
1210                         if (ecdhp == NULL)
1211                                 {
1212                                 al=SSL_AD_HANDSHAKE_FAILURE;
1213                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1214                                 goto f_err;
1215                                 }
1216
1217                         if (s->s3->tmp.ecdh != NULL)
1218                                 {
1219                                 EC_KEY_free(s->s3->tmp.ecdh); 
1220                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1221                                 goto err;
1222                                 }
1223
1224                         /* Duplicate the ECDH structure. */
1225                         if (ecdhp == NULL)
1226                                 {
1227                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1228                                 goto err;
1229                                 }
1230                         if (!EC_KEY_up_ref(ecdhp))
1231                                 {
1232                                 SSLerr(SSL_F_SSL3_CTRL,ERR_R_ECDH_LIB);
1233                                 goto err;
1234                                 }
1235                         ecdh = ecdhp;
1236
1237                         s->s3->tmp.ecdh=ecdh;
1238                         if ((ecdh->pub_key == NULL) ||
1239                             (ecdh->priv_key == NULL) ||
1240                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1241                                 {
1242                                 if(!EC_KEY_generate_key(ecdh))
1243                                     {
1244                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1245                                     goto err;
1246                                     }
1247                                 }
1248
1249                         if ((ecdh->group == NULL) ||
1250                             (ecdh->pub_key == NULL) ||
1251                             (ecdh->priv_key == NULL))
1252                                 {
1253                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1254                                 goto err;
1255                                 }
1256
1257                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1258                             (EC_GROUP_get_degree(ecdh->group) > 163)) 
1259                                 {
1260                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1261                                 goto err;
1262                                 }
1263
1264                         /* XXX: For now, we only support ephemeral ECDH
1265                          * keys over named (not generic) curves. For 
1266                          * supported named curves, curve_id is non-zero.
1267                          */
1268                         if ((curve_id = 
1269                             nid2curve_id(EC_GROUP_get_nid(ecdh->group)))
1270                             == 0)
1271                                 {
1272                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1273                                 goto err;
1274                                 }
1275
1276                         /* Encode the public key.
1277                          * First check the size of encoding and
1278                          * allocate memory accordingly.
1279                          */
1280                         encodedlen = EC_POINT_point2oct(ecdh->group, 
1281                             ecdh->pub_key, 
1282                             POINT_CONVERSION_UNCOMPRESSED, 
1283                             NULL, 0, NULL);
1284
1285                         encodedPoint = (unsigned char *) 
1286                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1287                         bn_ctx = BN_CTX_new();
1288                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1289                                 {
1290                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1291                                 goto err;
1292                                 }
1293
1294
1295                         encodedlen = EC_POINT_point2oct(ecdh->group, 
1296                             ecdh->pub_key, 
1297                             POINT_CONVERSION_UNCOMPRESSED, 
1298                             encodedPoint, encodedlen, bn_ctx);
1299
1300                         if (encodedlen == 0) 
1301                                 {
1302                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1303                                 goto err;
1304                                 }
1305
1306                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1307
1308                         /* XXX: For now, we only support named (not 
1309                          * generic) curves in ECDH ephemeral key exchanges.
1310                          * In this situation, we need three additional bytes
1311                          * to encode the entire ServerECDHParams
1312                          * structure. 
1313                          */
1314                         n = 3 + encodedlen;
1315
1316                         /* We'll generate the serverKeyExchange message
1317                          * explicitly so we can set these to NULLs
1318                          */
1319                         r[0]=NULL;
1320                         r[1]=NULL;
1321                         r[2]=NULL;
1322                         }
1323                 else 
1324 #endif /* !OPENSSL_NO_ECDH */
1325                         {
1326                         al=SSL_AD_HANDSHAKE_FAILURE;
1327                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1328                         goto f_err;
1329                         }
1330                 for (i=0; r[i] != NULL; i++)
1331                         {
1332                         nr[i]=BN_num_bytes(r[i]);
1333                         n+=2+nr[i];
1334                         }
1335
1336                 if (!(s->s3->tmp.new_cipher->algorithms & SSL_aNULL))
1337                         {
1338                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher))
1339                                 == NULL)
1340                                 {
1341                                 al=SSL_AD_DECODE_ERROR;
1342                                 goto f_err;
1343                                 }
1344                         kn=EVP_PKEY_size(pkey);
1345                         }
1346                 else
1347                         {
1348                         pkey=NULL;
1349                         kn=0;
1350                         }
1351
1352                 if (!BUF_MEM_grow_clean(buf,n+4+kn))
1353                         {
1354                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1355                         goto err;
1356                         }
1357                 d=(unsigned char *)s->init_buf->data;
1358                 p= &(d[4]);
1359
1360                 for (i=0; r[i] != NULL; i++)
1361                         {
1362                         s2n(nr[i],p);
1363                         BN_bn2bin(r[i],p);
1364                         p+=nr[i];
1365                         }
1366
1367 #ifndef OPENSSL_NO_ECDH
1368                 if (type & SSL_kECDHE) 
1369                         {
1370                         /* XXX: For now, we only support named (not generic) curves.
1371                          * In this situation, the serverKeyExchange message has:
1372                          * [1 byte CurveType], [1 byte CurveName]
1373                          * [1 byte length of encoded point], followed by
1374                          * the actual encoded point itself
1375                          */
1376                         *p = NAMED_CURVE_TYPE;
1377                         p += 1;
1378                         *p = curve_id;
1379                         p += 1;
1380                         *p = encodedlen;
1381                         p += 1;
1382                         memcpy((unsigned char*)p, 
1383                             (unsigned char *)encodedPoint, 
1384                             encodedlen);
1385                         OPENSSL_free(encodedPoint);
1386                         p += encodedlen;
1387                         }
1388 #endif
1389
1390                 /* not anonymous */
1391                 if (pkey != NULL)
1392                         {
1393                         /* n is the length of the params, they start at &(d[4])
1394                          * and p points to the space at the end. */
1395 #ifndef OPENSSL_NO_RSA
1396                         if (pkey->type == EVP_PKEY_RSA)
1397                                 {
1398                                 q=md_buf;
1399                                 j=0;
1400                                 for (num=2; num > 0; num--)
1401                                         {
1402                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1403                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1404                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1405                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1406                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1407                                         EVP_DigestFinal_ex(&md_ctx,q,
1408                                                 (unsigned int *)&i);
1409                                         q+=i;
1410                                         j+=i;
1411                                         }
1412                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1413                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1414                                         {
1415                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1416                                         goto err;
1417                                         }
1418                                 s2n(u,p);
1419                                 n+=u+2;
1420                                 }
1421                         else
1422 #endif
1423 #if !defined(OPENSSL_NO_DSA)
1424                                 if (pkey->type == EVP_PKEY_DSA)
1425                                 {
1426                                 /* lets do DSS */
1427                                 EVP_SignInit_ex(&md_ctx,EVP_dss1(), NULL);
1428                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1429                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1430                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1431                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1432                                         (unsigned int *)&i,pkey))
1433                                         {
1434                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_DSA);
1435                                         goto err;
1436                                         }
1437                                 s2n(i,p);
1438                                 n+=i+2;
1439                                 }
1440                         else
1441 #endif
1442 #if !defined(OPENSSL_NO_ECDSA)
1443                                 if (pkey->type == EVP_PKEY_EC)
1444                                 {
1445                                 /* let's do ECDSA */
1446                                 EVP_SignInit_ex(&md_ctx,EVP_ecdsa(), NULL);
1447                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1448                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1449                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1450                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1451                                         (unsigned int *)&i,pkey))
1452                                         {
1453                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_ECDSA);
1454                                         goto err;
1455                                         }
1456                                 s2n(i,p);
1457                                 n+=i+2;
1458                                 }
1459                         else
1460 #endif
1461                                 {
1462                                 /* Is this error check actually needed? */
1463                                 al=SSL_AD_HANDSHAKE_FAILURE;
1464                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1465                                 goto f_err;
1466                                 }
1467                         }
1468
1469                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1470                 l2n3(n,d);
1471
1472                 /* we should now have things packed up, so lets send
1473                  * it off */
1474                 s->init_num=n+4;
1475                 s->init_off=0;
1476                 }
1477
1478         s->state = SSL3_ST_SW_KEY_EXCH_B;
1479         EVP_MD_CTX_cleanup(&md_ctx);
1480         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1481 f_err:
1482         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1483 err:
1484 #ifndef OPENSSL_NO_ECDH
1485         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
1486         BN_CTX_free(bn_ctx);
1487 #endif
1488         EVP_MD_CTX_cleanup(&md_ctx);
1489         return(-1);
1490         }
1491
1492 static int ssl3_send_certificate_request(SSL *s)
1493         {
1494         unsigned char *p,*d;
1495         int i,j,nl,off,n;
1496         STACK_OF(X509_NAME) *sk=NULL;
1497         X509_NAME *name;
1498         BUF_MEM *buf;
1499
1500         if (s->state == SSL3_ST_SW_CERT_REQ_A)
1501                 {
1502                 buf=s->init_buf;
1503
1504                 d=p=(unsigned char *)&(buf->data[4]);
1505
1506                 /* get the list of acceptable cert types */
1507                 p++;
1508                 n=ssl3_get_req_cert_type(s,p);
1509                 d[0]=n;
1510                 p+=n;
1511                 n++;
1512
1513                 off=n;
1514                 p+=2;
1515                 n+=2;
1516
1517                 sk=SSL_get_client_CA_list(s);
1518                 nl=0;
1519                 if (sk != NULL)
1520                         {
1521                         for (i=0; i<sk_X509_NAME_num(sk); i++)
1522                                 {
1523                                 name=sk_X509_NAME_value(sk,i);
1524                                 j=i2d_X509_NAME(name,NULL);
1525                                 if (!BUF_MEM_grow_clean(buf,4+n+j+2))
1526                                         {
1527                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
1528                                         goto err;
1529                                         }
1530                                 p=(unsigned char *)&(buf->data[4+n]);
1531                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
1532                                         {
1533                                         s2n(j,p);
1534                                         i2d_X509_NAME(name,&p);
1535                                         n+=2+j;
1536                                         nl+=2+j;
1537                                         }
1538                                 else
1539                                         {
1540                                         d=p;
1541                                         i2d_X509_NAME(name,&p);
1542                                         j-=2; s2n(j,d); j+=2;
1543                                         n+=j;
1544                                         nl+=j;
1545                                         }
1546                                 }
1547                         }
1548                 /* else no CA names */
1549                 p=(unsigned char *)&(buf->data[4+off]);
1550                 s2n(nl,p);
1551
1552                 d=(unsigned char *)buf->data;
1553                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
1554                 l2n3(n,d);
1555
1556                 /* we should now have things packed up, so lets send
1557                  * it off */
1558
1559                 s->init_num=n+4;
1560                 s->init_off=0;
1561 #ifdef NETSCAPE_HANG_BUG
1562                 p=(unsigned char *)s->init_buf->data + s->init_num;
1563
1564                 /* do the header */
1565                 *(p++)=SSL3_MT_SERVER_DONE;
1566                 *(p++)=0;
1567                 *(p++)=0;
1568                 *(p++)=0;
1569                 s->init_num += 4;
1570 #endif
1571
1572                 }
1573
1574         /* SSL3_ST_SW_CERT_REQ_B */
1575         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1576 err:
1577         return(-1);
1578         }
1579
1580
1581 static const int KDF1_SHA1_len = 20;
1582 static void *KDF1_SHA1(void *in, size_t inlen, void *out, size_t outlen)
1583         {
1584 #ifndef OPENSSL_NO_SHA
1585         if (outlen != SHA_DIGEST_LENGTH)
1586                 return NULL;
1587         return SHA1(in, inlen, out);
1588 #else
1589         return NULL;
1590 #endif
1591         }
1592
1593 static int ssl3_get_client_key_exchange(SSL *s)
1594         {
1595         int i,al,ok;
1596         long n;
1597         unsigned long l;
1598         unsigned char *p;
1599 #ifndef OPENSSL_NO_RSA
1600         RSA *rsa=NULL;
1601         EVP_PKEY *pkey=NULL;
1602 #endif
1603 #ifndef OPENSSL_NO_DH
1604         BIGNUM *pub=NULL;
1605         DH *dh_srvr;
1606 #endif
1607 #ifndef OPENSSL_NO_KRB5
1608         KSSL_ERR kssl_err;
1609 #endif /* OPENSSL_NO_KRB5 */
1610
1611 #ifndef OPENSSL_NO_ECDH
1612         EC_KEY *srvr_ecdh = NULL;
1613         EVP_PKEY *clnt_pub_pkey = NULL;
1614         EC_POINT *clnt_ecpoint = NULL;
1615         BN_CTX *bn_ctx = NULL; 
1616 #endif
1617
1618         n=ssl3_get_message(s,
1619                 SSL3_ST_SR_KEY_EXCH_A,
1620                 SSL3_ST_SR_KEY_EXCH_B,
1621                 SSL3_MT_CLIENT_KEY_EXCHANGE,
1622                 2048, /* ??? */
1623                 &ok);
1624
1625         if (!ok) return((int)n);
1626         p=(unsigned char *)s->init_msg;
1627
1628         l=s->s3->tmp.new_cipher->algorithms;
1629
1630 #ifndef OPENSSL_NO_RSA
1631         if (l & SSL_kRSA)
1632                 {
1633                 /* FIX THIS UP EAY EAY EAY EAY */
1634                 if (s->s3->tmp.use_rsa_tmp)
1635                         {
1636                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
1637                                 rsa=s->cert->rsa_tmp;
1638                         /* Don't do a callback because rsa_tmp should
1639                          * be sent already */
1640                         if (rsa == NULL)
1641                                 {
1642                                 al=SSL_AD_HANDSHAKE_FAILURE;
1643                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
1644                                 goto f_err;
1645
1646                                 }
1647                         }
1648                 else
1649                         {
1650                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
1651                         if (    (pkey == NULL) ||
1652                                 (pkey->type != EVP_PKEY_RSA) ||
1653                                 (pkey->pkey.rsa == NULL))
1654                                 {
1655                                 al=SSL_AD_HANDSHAKE_FAILURE;
1656                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
1657                                 goto f_err;
1658                                 }
1659                         rsa=pkey->pkey.rsa;
1660                         }
1661
1662                 /* TLS */
1663                 if (s->version > SSL3_VERSION)
1664                         {
1665                         n2s(p,i);
1666                         if (n != i+2)
1667                                 {
1668                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
1669                                         {
1670                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
1671                                         goto err;
1672                                         }
1673                                 else
1674                                         p-=2;
1675                                 }
1676                         else
1677                                 n=i;
1678                         }
1679
1680                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
1681
1682                 al = -1;
1683                 
1684                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
1685                         {
1686                         al=SSL_AD_DECODE_ERROR;
1687                         /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
1688                         }
1689
1690                 if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
1691                         {
1692                         /* The premaster secret must contain the same version number as the
1693                          * ClientHello to detect version rollback attacks (strangely, the
1694                          * protocol does not offer such protection for DH ciphersuites).
1695                          * However, buggy clients exist that send the negotiated protocol
1696                          * version instead if the server does not support the requested
1697                          * protocol version.
1698                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
1699                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
1700                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
1701                                 {
1702                                 al=SSL_AD_DECODE_ERROR;
1703                                 /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
1704
1705                                 /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
1706                                  * (http://eprint.iacr.org/2003/052/) exploits the version
1707                                  * number check as a "bad version oracle" -- an alert would
1708                                  * reveal that the plaintext corresponding to some ciphertext
1709                                  * made up by the adversary is properly formatted except
1710                                  * that the version number is wrong.  To avoid such attacks,
1711                                  * we should treat this just like any other decryption error. */
1712                                 }
1713                         }
1714
1715                 if (al != -1)
1716                         {
1717                         /* Some decryption failure -- use random value instead as countermeasure
1718                          * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
1719                          * (see RFC 2246, section 7.4.7.1). */
1720                         ERR_clear_error();
1721                         i = SSL_MAX_MASTER_KEY_LENGTH;
1722                         p[0] = s->client_version >> 8;
1723                         p[1] = s->client_version & 0xff;
1724                         RAND_pseudo_bytes(p+2, i-2); /* should be RAND_bytes, but we cannot work around a failure */
1725                         }
1726         
1727                 s->session->master_key_length=
1728                         s->method->ssl3_enc->generate_master_secret(s,
1729                                 s->session->master_key,
1730                                 p,i);
1731                 OPENSSL_cleanse(p,i);
1732                 }
1733         else
1734 #endif
1735 #ifndef OPENSSL_NO_DH
1736                 if (l & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
1737                 {
1738                 n2s(p,i);
1739                 if (n != i+2)
1740                         {
1741                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
1742                                 {
1743                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
1744                                 goto err;
1745                                 }
1746                         else
1747                                 {
1748                                 p-=2;
1749                                 i=(int)n;
1750                                 }
1751                         }
1752
1753                 if (n == 0L) /* the parameters are in the cert */
1754                         {
1755                         al=SSL_AD_HANDSHAKE_FAILURE;
1756                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
1757                         goto f_err;
1758                         }
1759                 else
1760                         {
1761                         if (s->s3->tmp.dh == NULL)
1762                                 {
1763                                 al=SSL_AD_HANDSHAKE_FAILURE;
1764                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1765                                 goto f_err;
1766                                 }
1767                         else
1768                                 dh_srvr=s->s3->tmp.dh;
1769                         }
1770
1771                 pub=BN_bin2bn(p,i,NULL);
1772                 if (pub == NULL)
1773                         {
1774                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
1775                         goto err;
1776                         }
1777
1778                 i=DH_compute_key(p,pub,dh_srvr);
1779
1780                 if (i <= 0)
1781                         {
1782                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
1783                         goto err;
1784                         }
1785
1786                 DH_free(s->s3->tmp.dh);
1787                 s->s3->tmp.dh=NULL;
1788
1789                 BN_clear_free(pub);
1790                 pub=NULL;
1791                 s->session->master_key_length=
1792                         s->method->ssl3_enc->generate_master_secret(s,
1793                                 s->session->master_key,p,i);
1794                 OPENSSL_cleanse(p,i);
1795                 }
1796         else
1797 #endif
1798 #ifndef OPENSSL_NO_KRB5
1799         if (l & SSL_kKRB5)
1800                 {
1801                 krb5_error_code         krb5rc;
1802                 krb5_data               enc_ticket;
1803                 krb5_data               authenticator;
1804                 krb5_data               enc_pms;
1805                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
1806                 EVP_CIPHER_CTX          ciph_ctx;
1807                 EVP_CIPHER              *enc = NULL;
1808                 unsigned char           iv[EVP_MAX_IV_LENGTH];
1809                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
1810                                                + EVP_MAX_BLOCK_LENGTH];
1811                 int                     padl, outl;
1812                 krb5_timestamp          authtime = 0;
1813                 krb5_ticket_times       ttimes;
1814
1815                 EVP_CIPHER_CTX_init(&ciph_ctx);
1816
1817                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
1818
1819                 n2s(p,i);
1820                 enc_ticket.length = i;
1821                 enc_ticket.data = (char *)p;
1822                 p+=enc_ticket.length;
1823
1824                 n2s(p,i);
1825                 authenticator.length = i;
1826                 authenticator.data = (char *)p;
1827                 p+=authenticator.length;
1828
1829                 n2s(p,i);
1830                 enc_pms.length = i;
1831                 enc_pms.data = (char *)p;
1832                 p+=enc_pms.length;
1833
1834                 /* Note that the length is checked again below,
1835                 ** after decryption
1836                 */
1837                 if(enc_pms.length > sizeof pms)
1838                         {
1839                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1840                                SSL_R_DATA_LENGTH_TOO_LONG);
1841                         goto err;
1842                         }
1843
1844                 if (n != enc_ticket.length + authenticator.length +
1845                                                 enc_pms.length + 6)
1846                         {
1847                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1848                                 SSL_R_DATA_LENGTH_TOO_LONG);
1849                         goto err;
1850                         }
1851
1852                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
1853                                         &kssl_err)) != 0)
1854                         {
1855 #ifdef KSSL_DEBUG
1856                         printf("kssl_sget_tkt rtn %d [%d]\n",
1857                                 krb5rc, kssl_err.reason);
1858                         if (kssl_err.text)
1859                                 printf("kssl_err text= %s\n", kssl_err.text);
1860 #endif  /* KSSL_DEBUG */
1861                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1862                                 kssl_err.reason);
1863                         goto err;
1864                         }
1865
1866                 /*  Note: no authenticator is not considered an error,
1867                 **  but will return authtime == 0.
1868                 */
1869                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
1870                                         &authtime, &kssl_err)) != 0)
1871                         {
1872 #ifdef KSSL_DEBUG
1873                         printf("kssl_check_authent rtn %d [%d]\n",
1874                                 krb5rc, kssl_err.reason);
1875                         if (kssl_err.text)
1876                                 printf("kssl_err text= %s\n", kssl_err.text);
1877 #endif  /* KSSL_DEBUG */
1878                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE,
1879                                 kssl_err.reason);
1880                         goto err;
1881                         }
1882
1883                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
1884                         {
1885                         SSLerr(SSL_F_SSL3_SEND_CLIENT_KEY_EXCHANGE, krb5rc);
1886                         goto err;
1887                         }
1888
1889 #ifdef KSSL_DEBUG
1890                 kssl_ctx_show(kssl_ctx);
1891 #endif  /* KSSL_DEBUG */
1892
1893                 enc = kssl_map_enc(kssl_ctx->enctype);
1894                 if (enc == NULL)
1895                     goto err;
1896
1897                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
1898
1899                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
1900                         {
1901                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1902                                 SSL_R_DECRYPTION_FAILED);
1903                         goto err;
1904                         }
1905                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
1906                                         (unsigned char *)enc_pms.data, enc_pms.length))
1907                         {
1908                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1909                                 SSL_R_DECRYPTION_FAILED);
1910                         goto err;
1911                         }
1912                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
1913                         {
1914                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1915                                 SSL_R_DATA_LENGTH_TOO_LONG);
1916                         goto err;
1917                         }
1918                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
1919                         {
1920                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1921                                 SSL_R_DECRYPTION_FAILED);
1922                         goto err;
1923                         }
1924                 outl += padl;
1925                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
1926                         {
1927                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1928                                 SSL_R_DATA_LENGTH_TOO_LONG);
1929                         goto err;
1930                         }
1931                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
1932
1933                 s->session->master_key_length=
1934                         s->method->ssl3_enc->generate_master_secret(s,
1935                                 s->session->master_key, pms, outl);
1936
1937                 if (kssl_ctx->client_princ)
1938                         {
1939                         int len = strlen(kssl_ctx->client_princ);
1940                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
1941                                 {
1942                                 s->session->krb5_client_princ_len = len;
1943                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
1944                                 }
1945                         }
1946
1947
1948                 /*  Was doing kssl_ctx_free() here,
1949                 **  but it caused problems for apache.
1950                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
1951                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
1952                 */
1953                 }
1954         else
1955 #endif  /* OPENSSL_NO_KRB5 */
1956
1957 #ifndef OPENSSL_NO_ECDH
1958                 if ((l & SSL_kECDH) || (l & SSL_kECDHE))
1959                 {
1960                 int ret = 1;
1961
1962                 /* initialize structures for server's ECDH key pair */
1963                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
1964                         {
1965                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1966                             ERR_R_MALLOC_FAILURE);
1967                         goto err;
1968                         }
1969
1970                 /* Let's get server private key and group information */
1971                 if (l & SSL_kECDH) 
1972                         { 
1973                         /* use the certificate */
1974                         srvr_ecdh->group = s->cert->key->privatekey-> \
1975                             pkey.eckey->group;
1976                         srvr_ecdh->priv_key = s->cert->key->privatekey-> \
1977                             pkey.eckey->priv_key;
1978                         }
1979                 else
1980                         {
1981                         /* use the ephermeral values we saved when
1982                          * generating the ServerKeyExchange msg.
1983                          */
1984                         srvr_ecdh->group = s->s3->tmp.ecdh->group;
1985                         srvr_ecdh->priv_key = s->s3->tmp.ecdh->priv_key;
1986                         }
1987
1988                 /* Let's get client's public key */
1989                 if ((clnt_ecpoint = EC_POINT_new(srvr_ecdh->group))
1990                     == NULL) 
1991                         {
1992                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
1993                             ERR_R_MALLOC_FAILURE);
1994                         goto err;
1995                         }
1996
1997                 if (n == 0L) 
1998                         {
1999                         /* Client Publickey was in Client Certificate */
2000
2001                          if (l & SSL_kECDHE) 
2002                                  {
2003                                  al=SSL_AD_HANDSHAKE_FAILURE;
2004                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2005                                  goto f_err;
2006                                  }
2007                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2008                             == NULL) || 
2009                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2010                                 {
2011                                 /* XXX: For now, we do not support client
2012                                  * authentication using ECDH certificates
2013                                  * so this branch (n == 0L) of the code is
2014                                  * never executed. When that support is
2015                                  * added, we ought to ensure the key 
2016                                  * received in the certificate is 
2017                                  * authorized for key agreement.
2018                                  * ECDH_compute_key implicitly checks that
2019                                  * the two ECDH shares are for the same
2020                                  * group.
2021                                  */
2022                                 al=SSL_AD_HANDSHAKE_FAILURE;
2023                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2024                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2025                                 goto f_err;
2026                                 }
2027
2028                         EC_POINT_copy(clnt_ecpoint,
2029                             clnt_pub_pkey->pkey.eckey->pub_key);
2030                         ret = 2; /* Skip certificate verify processing */
2031                         }
2032                 else
2033                         {
2034                         /* Get client's public key from encoded point
2035                          * in the ClientKeyExchange message.
2036                          */
2037                         if ((bn_ctx = BN_CTX_new()) == NULL)
2038                                 {
2039                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2040                                     ERR_R_MALLOC_FAILURE);
2041                                 goto err;
2042                                 }
2043
2044                         /* Get encoded point length */
2045                         i = *p; 
2046                         p += 1;
2047                         if (EC_POINT_oct2point(srvr_ecdh->group, 
2048                             clnt_ecpoint, p, i, bn_ctx) == 0)
2049                                 {
2050                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2051                                     ERR_R_EC_LIB);
2052                                 goto err;
2053                                 }
2054                         /* p is pointing to somewhere in the buffer
2055                          * currently, so set it to the start 
2056                          */ 
2057                         p=(unsigned char *)s->init_buf->data;
2058                         }
2059
2060                 /* Compute the shared pre-master secret */
2061                 i = ECDH_compute_key(p, KDF1_SHA1_len, clnt_ecpoint, srvr_ecdh, KDF1_SHA1);
2062                 if (i <= 0)
2063                         {
2064                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2065                             ERR_R_ECDH_LIB);
2066                         goto err;
2067                         }
2068
2069                 EVP_PKEY_free(clnt_pub_pkey);
2070                 EC_POINT_free(clnt_ecpoint);
2071                 if (srvr_ecdh != NULL) 
2072                         {
2073                         srvr_ecdh->priv_key = NULL;
2074                         srvr_ecdh->group = NULL;
2075                         EC_KEY_free(srvr_ecdh);
2076                         }
2077                 BN_CTX_free(bn_ctx);
2078
2079                 /* Compute the master secret */
2080                 s->session->master_key_length = s->method->ssl3_enc-> \
2081                     generate_master_secret(s, s->session->master_key, p, i);
2082                 
2083                 OPENSSL_cleanse(p, i);
2084                 return (ret);
2085                 }
2086         else
2087 #endif
2088                 {
2089                 al=SSL_AD_HANDSHAKE_FAILURE;
2090                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2091                                 SSL_R_UNKNOWN_CIPHER_TYPE);
2092                 goto f_err;
2093                 }
2094
2095         return(1);
2096 f_err:
2097         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2098 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH)
2099 err:
2100 #endif
2101 #ifndef OPENSSL_NO_ECDH
2102         EVP_PKEY_free(clnt_pub_pkey);
2103         EC_POINT_free(clnt_ecpoint);
2104         if (srvr_ecdh != NULL) 
2105                 {
2106                 srvr_ecdh->priv_key = NULL;
2107                 srvr_ecdh->group = NULL;
2108                 EC_KEY_free(srvr_ecdh);
2109                 }
2110         BN_CTX_free(bn_ctx);
2111 #endif
2112         return(-1);
2113         }
2114
2115 static int ssl3_get_cert_verify(SSL *s)
2116         {
2117         EVP_PKEY *pkey=NULL;
2118         unsigned char *p;
2119         int al,ok,ret=0;
2120         long n;
2121         int type=0,i,j;
2122         X509 *peer;
2123
2124         n=ssl3_get_message(s,
2125                 SSL3_ST_SR_CERT_VRFY_A,
2126                 SSL3_ST_SR_CERT_VRFY_B,
2127                 -1,
2128                 514, /* 514? */
2129                 &ok);
2130
2131         if (!ok) return((int)n);
2132
2133         if (s->session->peer != NULL)
2134                 {
2135                 peer=s->session->peer;
2136                 pkey=X509_get_pubkey(peer);
2137                 type=X509_certificate_type(peer,pkey);
2138                 }
2139         else
2140                 {
2141                 peer=NULL;
2142                 pkey=NULL;
2143                 }
2144
2145         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
2146                 {
2147                 s->s3->tmp.reuse_message=1;
2148                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
2149                         {
2150                         al=SSL_AD_UNEXPECTED_MESSAGE;
2151                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
2152                         goto f_err;
2153                         }
2154                 ret=1;
2155                 goto end;
2156                 }
2157
2158         if (peer == NULL)
2159                 {
2160                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
2161                 al=SSL_AD_UNEXPECTED_MESSAGE;
2162                 goto f_err;
2163                 }
2164
2165         if (!(type & EVP_PKT_SIGN))
2166                 {
2167                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2168                 al=SSL_AD_ILLEGAL_PARAMETER;
2169                 goto f_err;
2170                 }
2171
2172         if (s->s3->change_cipher_spec)
2173                 {
2174                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
2175                 al=SSL_AD_UNEXPECTED_MESSAGE;
2176                 goto f_err;
2177                 }
2178
2179         /* we now have a signature that we need to verify */
2180         p=(unsigned char *)s->init_msg;
2181         n2s(p,i);
2182         n-=2;
2183         if (i > n)
2184                 {
2185                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
2186                 al=SSL_AD_DECODE_ERROR;
2187                 goto f_err;
2188                 }
2189
2190         j=EVP_PKEY_size(pkey);
2191         if ((i > j) || (n > j) || (n <= 0))
2192                 {
2193                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
2194                 al=SSL_AD_DECODE_ERROR;
2195                 goto f_err;
2196                 }
2197
2198 #ifndef OPENSSL_NO_RSA 
2199         if (pkey->type == EVP_PKEY_RSA)
2200                 {
2201                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
2202                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
2203                                                         pkey->pkey.rsa);
2204                 if (i < 0)
2205                         {
2206                         al=SSL_AD_DECRYPT_ERROR;
2207                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
2208                         goto f_err;
2209                         }
2210                 if (i == 0)
2211                         {
2212                         al=SSL_AD_DECRYPT_ERROR;
2213                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
2214                         goto f_err;
2215                         }
2216                 }
2217         else
2218 #endif
2219 #ifndef OPENSSL_NO_DSA
2220                 if (pkey->type == EVP_PKEY_DSA)
2221                 {
2222                 j=DSA_verify(pkey->save_type,
2223                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2224                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
2225                 if (j <= 0)
2226                         {
2227                         /* bad signature */
2228                         al=SSL_AD_DECRYPT_ERROR;
2229                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
2230                         goto f_err;
2231                         }
2232                 }
2233         else
2234 #endif
2235 #ifndef OPENSSL_NO_ECDSA
2236                 if (pkey->type == EVP_PKEY_EC)
2237                 {
2238                 j=ECDSA_verify(pkey->save_type,
2239                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
2240                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.eckey);
2241                 if (j <= 0)
2242                         {
2243                         /* bad signature */
2244                         al=SSL_AD_DECRYPT_ERROR;
2245                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
2246                             SSL_R_BAD_ECDSA_SIGNATURE);
2247                         goto f_err;
2248                         }
2249                 }
2250         else
2251 #endif
2252                 {
2253                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
2254                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
2255                 goto f_err;
2256                 }
2257
2258
2259         ret=1;
2260         if (0)
2261                 {
2262 f_err:
2263                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2264                 }
2265 end:
2266         EVP_PKEY_free(pkey);
2267         return(ret);
2268         }
2269
2270 static int ssl3_get_client_certificate(SSL *s)
2271         {
2272         int i,ok,al,ret= -1;
2273         X509 *x=NULL;
2274         unsigned long l,nc,llen,n;
2275         unsigned char *p,*d,*q;
2276         STACK_OF(X509) *sk=NULL;
2277
2278         n=ssl3_get_message(s,
2279                 SSL3_ST_SR_CERT_A,
2280                 SSL3_ST_SR_CERT_B,
2281                 -1,
2282                 s->max_cert_list,
2283                 &ok);
2284
2285         if (!ok) return((int)n);
2286
2287         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
2288                 {
2289                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
2290                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2291                         {
2292                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2293                         al=SSL_AD_HANDSHAKE_FAILURE;
2294                         goto f_err;
2295                         }
2296                 /* If tls asked for a client cert, the client must return a 0 list */
2297                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
2298                         {
2299                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
2300                         al=SSL_AD_UNEXPECTED_MESSAGE;
2301                         goto f_err;
2302                         }
2303                 s->s3->tmp.reuse_message=1;
2304                 return(1);
2305                 }
2306
2307         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
2308                 {
2309                 al=SSL_AD_UNEXPECTED_MESSAGE;
2310                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
2311                 goto f_err;
2312                 }
2313         d=p=(unsigned char *)s->init_msg;
2314
2315         if ((sk=sk_X509_new_null()) == NULL)
2316                 {
2317                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
2318                 goto err;
2319                 }
2320
2321         n2l3(p,llen);
2322         if (llen+3 != n)
2323                 {
2324                 al=SSL_AD_DECODE_ERROR;
2325                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
2326                 goto f_err;
2327                 }
2328         for (nc=0; nc<llen; )
2329                 {
2330                 n2l3(p,l);
2331                 if ((l+nc+3) > llen)
2332                         {
2333                         al=SSL_AD_DECODE_ERROR;
2334                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
2335                         goto f_err;
2336                         }
2337
2338                 q=p;
2339                 x=d2i_X509(NULL,&p,l);
2340                 if (x == NULL)
2341                         {
2342                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
2343                         goto err;
2344                         }
2345                 if (p != (q+l))
2346                         {
2347                         al=SSL_AD_DECODE_ERROR;
2348                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
2349                         goto f_err;
2350                         }
2351                 if (!sk_X509_push(sk,x))
2352                         {
2353                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
2354                         goto err;
2355                         }
2356                 x=NULL;
2357                 nc+=l+3;
2358                 }
2359
2360         if (sk_X509_num(sk) <= 0)
2361                 {
2362                 /* TLS does not mind 0 certs returned */
2363                 if (s->version == SSL3_VERSION)
2364                         {
2365                         al=SSL_AD_HANDSHAKE_FAILURE;
2366                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
2367                         goto f_err;
2368                         }
2369                 /* Fail for TLS only if we required a certificate */
2370                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
2371                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
2372                         {
2373                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
2374                         al=SSL_AD_HANDSHAKE_FAILURE;
2375                         goto f_err;
2376                         }
2377                 }
2378         else
2379                 {
2380                 i=ssl_verify_cert_chain(s,sk);
2381                 if (!i)
2382                         {
2383                         al=ssl_verify_alarm_type(s->verify_result);
2384                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
2385                         goto f_err;
2386                         }
2387                 }
2388
2389         if (s->session->peer != NULL) /* This should not be needed */
2390                 X509_free(s->session->peer);
2391         s->session->peer=sk_X509_shift(sk);
2392         s->session->verify_result = s->verify_result;
2393
2394         /* With the current implementation, sess_cert will always be NULL
2395          * when we arrive here. */
2396         if (s->session->sess_cert == NULL)
2397                 {
2398                 s->session->sess_cert = ssl_sess_cert_new();
2399                 if (s->session->sess_cert == NULL)
2400                         {
2401                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
2402                         goto err;
2403                         }
2404                 }
2405         if (s->session->sess_cert->cert_chain != NULL)
2406                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
2407         s->session->sess_cert->cert_chain=sk;
2408         /* Inconsistency alert: cert_chain does *not* include the
2409          * peer's own certificate, while we do include it in s3_clnt.c */
2410
2411         sk=NULL;
2412
2413         ret=1;
2414         if (0)
2415                 {
2416 f_err:
2417                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
2418                 }
2419 err:
2420         if (x != NULL) X509_free(x);
2421         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
2422         return(ret);
2423         }
2424
2425 int ssl3_send_server_certificate(SSL *s)
2426         {
2427         unsigned long l;
2428         X509 *x;
2429
2430         if (s->state == SSL3_ST_SW_CERT_A)
2431                 {
2432                 x=ssl_get_server_send_cert(s);
2433                 if (x == NULL &&
2434                         /* VRS: allow null cert if auth == KRB5 */
2435                         (s->s3->tmp.new_cipher->algorithms
2436                                 & (SSL_MKEY_MASK|SSL_AUTH_MASK))
2437                         != (SSL_aKRB5|SSL_kKRB5))
2438                         {
2439                         SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
2440                         return(0);
2441                         }
2442
2443                 l=ssl3_output_cert_chain(s,x);
2444                 s->state=SSL3_ST_SW_CERT_B;
2445                 s->init_num=(int)l;
2446                 s->init_off=0;
2447                 }
2448
2449         /* SSL3_ST_SW_CERT_B */
2450         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2451         }
2452
2453
2454 #ifndef OPENSSL_NO_ECDH
2455 /* This is the complement of curve_id2nid in s3_clnt.c. */
2456 static int nid2curve_id(int nid)
2457 {
2458         /* ECC curves from draft-ietf-tls-ecc-01.txt (Mar 15, 2001) */
2459         switch (nid) {
2460         case NID_sect163k1: /* sect163k1 (1) */
2461                 return 1;
2462         case NID_sect163r1: /* sect163r1 (2) */
2463                 return 2;
2464         case NID_sect163r2: /* sect163r2 (3) */
2465                 return 3;
2466         case NID_sect193r1: /* sect193r1 (4) */ 
2467                 return 4;
2468         case NID_sect193r2: /* sect193r2 (5) */ 
2469                 return 5;
2470         case NID_sect233k1: /* sect233k1 (6) */
2471                 return 6;
2472         case NID_sect233r1: /* sect233r1 (7) */ 
2473                 return 7;
2474         case NID_sect239k1: /* sect239k1 (8) */ 
2475                 return 8;
2476         case NID_sect283k1: /* sect283k1 (9) */
2477                 return 9;
2478         case NID_sect283r1: /* sect283r1 (10) */ 
2479                 return 10;
2480         case NID_sect409k1: /* sect409k1 (11) */ 
2481                 return 11;
2482         case NID_sect409r1: /* sect409r1 (12) */
2483                 return 12;
2484         case NID_sect571k1: /* sect571k1 (13) */ 
2485                 return 13;
2486         case NID_sect571r1: /* sect571r1 (14) */ 
2487                 return 14;
2488         case NID_secp160k1: /* secp160k1 (15) */
2489                 return 15;
2490         case NID_secp160r1: /* secp160r1 (16) */ 
2491                 return 16;
2492         case NID_secp160r2: /* secp160r2 (17) */ 
2493                 return 17;
2494         case NID_secp192k1: /* secp192k1 (18) */
2495                 return 18;
2496         case NID_X9_62_prime192v1: /* secp192r1 (19) */ 
2497                 return 19;
2498         case NID_secp224k1: /* secp224k1 (20) */ 
2499                 return 20;
2500         case NID_secp224r1: /* secp224r1 (21) */
2501                 return 21;
2502         case NID_secp256k1: /* secp256k1 (22) */ 
2503                 return 22;
2504         case NID_X9_62_prime256v1: /* secp256r1 (23) */ 
2505                 return 23;
2506         case NID_secp384r1: /* secp384r1 (24) */
2507                 return 24;
2508         case NID_secp521r1:  /* secp521r1 (25) */       
2509                 return 25;
2510         default:
2511                 return 0;
2512         }
2513 }
2514 #endif