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