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