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