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