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