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