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