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