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