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