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