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