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