Fix session handling.
[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 <openssl/crypto.h>
156 #include "ssl_locl.h"
157 #include "kssl_lcl.h"
158 #include <openssl/buffer.h>
159 #include <openssl/rand.h>
160 #include <openssl/objects.h>
161 #include <openssl/evp.h>
162 #include <openssl/hmac.h>
163 #include <openssl/x509.h>
164 #ifndef OPENSSL_NO_DH
165 #include <openssl/dh.h>
166 #endif
167 #include <openssl/bn.h>
168 #ifndef OPENSSL_NO_KRB5
169 #include <openssl/krb5_asn.h>
170 #endif
171 #include <openssl/md5.h>
172
173 static const SSL_METHOD *ssl3_get_server_method(int ver);
174
175 static const SSL_METHOD *ssl3_get_server_method(int ver)
176         {
177         if (ver == SSL3_VERSION)
178                 return(SSLv3_server_method());
179         else
180                 return(NULL);
181         }
182
183 #ifndef OPENSSL_NO_SRP
184 static int SSL_check_srp_ext_ClientHello(SSL *s,int *ad)
185         {
186         int ret = SSL_ERROR_NONE;
187
188         *ad = SSL_AD_UNRECOGNIZED_NAME;
189
190         if ((s->s3->tmp.new_cipher->algorithm_mkey & SSL_kSRP) &&
191             (s->srp_ctx.TLS_ext_srp_username_callback != NULL))
192                 {
193                 if(s->srp_ctx.login == NULL)
194                         {
195                         /* There isn't any srp login extension !!! */
196                         ret = SSL3_AL_WARNING;
197                         *ad = SSL_AD_MISSING_SRP_USERNAME;
198                         }
199                 else
200                         {
201                         ret = SSL_srp_server_param_with_username(s,ad);
202                         }
203                 }
204         return ret;
205         }
206 #endif
207
208 IMPLEMENT_ssl3_meth_func(SSLv3_server_method,
209                         ssl3_accept,
210                         ssl_undefined_function,
211                         ssl3_get_server_method)
212
213 int ssl3_accept(SSL *s)
214         {
215         BUF_MEM *buf;
216         unsigned long alg_k,Time=(unsigned long)time(NULL);
217         void (*cb)(const SSL *ssl,int type,int val)=NULL;
218         int ret= -1;
219         int new_state,state,skip=0;
220 #ifndef OPENSSL_NO_SRP
221         int srp_no_username =0;
222 #endif
223
224         RAND_add(&Time,sizeof(Time),0);
225         ERR_clear_error();
226         clear_sys_error();
227
228         if (s->info_callback != NULL)
229                 cb=s->info_callback;
230         else if (s->ctx->info_callback != NULL)
231                 cb=s->ctx->info_callback;
232
233         /* init things to blank */
234         s->in_handshake++;
235         if (!SSL_in_init(s) || SSL_in_before(s)) SSL_clear(s);
236
237         if (s->cert == NULL)
238                 {
239                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_NO_CERTIFICATE_SET);
240                 return(-1);
241                 }
242
243         for (;;)
244                 {
245                 state=s->state;
246
247                 switch (s->state)
248                         {
249                 case SSL_ST_RENEGOTIATE:
250                         s->renegotiate=1;
251                         /* s->state=SSL_ST_ACCEPT; */
252
253                 case SSL_ST_BEFORE:
254                 case SSL_ST_ACCEPT:
255                 case SSL_ST_BEFORE|SSL_ST_ACCEPT:
256                 case SSL_ST_OK|SSL_ST_ACCEPT:
257
258                         s->server=1;
259                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
260
261                         if ((s->version>>8) != 3)
262                                 {
263                                 SSLerr(SSL_F_SSL3_ACCEPT, ERR_R_INTERNAL_ERROR);
264                                 return -1;
265                                 }
266                         s->type=SSL_ST_ACCEPT;
267
268                         if (s->init_buf == NULL)
269                                 {
270                                 if ((buf=BUF_MEM_new()) == NULL)
271                                         {
272                                         ret= -1;
273                                         goto end;
274                                         }
275                                 if (!BUF_MEM_grow(buf,SSL3_RT_MAX_PLAIN_LENGTH))
276                                         {
277                                         ret= -1;
278                                         goto end;
279                                         }
280                                 s->init_buf=buf;
281                                 }
282
283                         if (!ssl3_setup_buffers(s))
284                                 {
285                                 ret= -1;
286                                 goto end;
287                                 }
288
289                         s->init_num=0;
290
291                         if (s->state != SSL_ST_RENEGOTIATE)
292                                 {
293                                 /* Ok, we now need to push on a buffering BIO so that
294                                  * the output is sent in a way that TCP likes :-)
295                                  */
296                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
297                                 
298                                 ssl3_init_finished_mac(s);
299                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
300                                 s->ctx->stats.sess_accept++;
301                                 }
302                         else if (!s->s3->send_connection_binding &&
303                                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
304                                 {
305                                 /* Server attempting to renegotiate with
306                                  * client that doesn't support secure
307                                  * renegotiation.
308                                  */
309                                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
310                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
311                                 ret = -1;
312                                 goto end;
313                                 }
314                         else
315                                 {
316                                 /* s->state == SSL_ST_RENEGOTIATE,
317                                  * we will just send a HelloRequest */
318                                 s->ctx->stats.sess_accept_renegotiate++;
319                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
320                                 }
321                         break;
322
323                 case SSL3_ST_SW_HELLO_REQ_A:
324                 case SSL3_ST_SW_HELLO_REQ_B:
325
326                         s->shutdown=0;
327                         ret=ssl3_send_hello_request(s);
328                         if (ret <= 0) goto end;
329                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
330                         s->state=SSL3_ST_SW_FLUSH;
331                         s->init_num=0;
332
333                         ssl3_init_finished_mac(s);
334                         break;
335
336                 case SSL3_ST_SW_HELLO_REQ_C:
337                         s->state=SSL_ST_OK;
338                         break;
339
340                 case SSL3_ST_SR_CLNT_HELLO_A:
341                 case SSL3_ST_SR_CLNT_HELLO_B:
342                 case SSL3_ST_SR_CLNT_HELLO_C:
343 #ifndef OPENSSL_NO_SRP
344                 case SSL3_ST_SR_CLNT_HELLO_SRP_USERNAME:
345 #endif
346
347                         s->shutdown=0;
348                         ret=ssl3_get_client_hello(s);
349                         if (ret <= 0) goto end;
350 #ifndef OPENSSL_NO_SRP
351                         {
352                         int extension_error = 0,al;
353
354                         if ((al = SSL_check_srp_ext_ClientHello(s,&extension_error)) != SSL_ERROR_NONE)
355                                 {
356                                 ssl3_send_alert(s,al,extension_error);
357                                 if (extension_error == SSL_AD_MISSING_SRP_USERNAME)
358                                         {
359                                         if (srp_no_username) goto end;
360                                         ERR_clear_error();
361                                         srp_no_username = 1;
362                                         s->state=SSL3_ST_SR_CLNT_HELLO_SRP_USERNAME;
363                                         if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_START,1);
364                                         if ((ret=BIO_flush(s->wbio)) <= 0) goto end;
365                                         s->init_num=0;
366                                         break;
367                                         }
368                                 ret = -1;
369                                 SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_CLIENTHELLO_TLSEXT);
370                                 goto end;
371                                 }
372                         }
373 #endif
374                         
375                         s->renegotiate = 2;
376                         s->state=SSL3_ST_SW_SRVR_HELLO_A;
377                         s->init_num=0;
378                         break;
379
380                 case SSL3_ST_SW_SRVR_HELLO_A:
381                 case SSL3_ST_SW_SRVR_HELLO_B:
382                         ret=ssl3_send_server_hello(s);
383                         if (ret <= 0) goto end;
384 #ifndef OPENSSL_NO_TLSEXT
385                         if (s->hit)
386                                 {
387                                 if (s->tlsext_ticket_expected)
388                                         s->state=SSL3_ST_SW_SESSION_TICKET_A;
389                                 else
390                                         s->state=SSL3_ST_SW_CHANGE_A;
391                                 }
392 #else
393                         if (s->hit)
394                                         s->state=SSL3_ST_SW_CHANGE_A;
395 #endif
396                         else
397                                 s->state=SSL3_ST_SW_CERT_A;
398                         s->init_num=0;
399                         break;
400
401                 case SSL3_ST_SW_CERT_A:
402                 case SSL3_ST_SW_CERT_B:
403                         /* Check if it is anon DH or anon ECDH, */
404                         /* normal PSK or KRB5 or SRP */
405                         if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
406                                 && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK)
407                                 && !(s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5))
408                                 {
409                                 ret=ssl3_send_server_certificate(s);
410                                 if (ret <= 0) goto end;
411 #ifndef OPENSSL_NO_TLSEXT
412                                 if (s->tlsext_status_expected)
413                                         s->state=SSL3_ST_SW_CERT_STATUS_A;
414                                 else
415                                         s->state=SSL3_ST_SW_KEY_EXCH_A;
416                                 }
417                         else
418                                 {
419                                 skip = 1;
420                                 s->state=SSL3_ST_SW_KEY_EXCH_A;
421                                 }
422 #else
423                                 }
424                         else
425                                 skip=1;
426
427                         s->state=SSL3_ST_SW_KEY_EXCH_A;
428 #endif
429                         s->init_num=0;
430                         break;
431
432                 case SSL3_ST_SW_KEY_EXCH_A:
433                 case SSL3_ST_SW_KEY_EXCH_B:
434                         alg_k = s->s3->tmp.new_cipher->algorithm_mkey;
435
436                         /* clear this, it may get reset by
437                          * send_server_key_exchange */
438                         if ((s->options & SSL_OP_EPHEMERAL_RSA)
439 #ifndef OPENSSL_NO_KRB5
440                                 && !(alg_k & SSL_kKRB5)
441 #endif /* OPENSSL_NO_KRB5 */
442                                 )
443                                 /* option SSL_OP_EPHEMERAL_RSA sends temporary RSA key
444                                  * even when forbidden by protocol specs
445                                  * (handshake may fail as clients are not required to
446                                  * be able to handle this) */
447                                 s->s3->tmp.use_rsa_tmp=1;
448                         else
449                                 s->s3->tmp.use_rsa_tmp=0;
450
451
452                         /* only send if a DH key exchange, fortezza or
453                          * RSA but we have a sign only certificate
454                          *
455                          * PSK: may send PSK identity hints
456                          *
457                          * For ECC ciphersuites, we send a serverKeyExchange
458                          * message only if the cipher suite is either
459                          * ECDH-anon or ECDHE. In other cases, the
460                          * server certificate contains the server's
461                          * public key for key exchange.
462                          */
463                         if (s->s3->tmp.use_rsa_tmp
464                         /* PSK: send ServerKeyExchange if PSK identity
465                          * hint if provided */
466 #ifndef OPENSSL_NO_PSK
467                             || ((alg_k & SSL_kPSK) && s->ctx->psk_identity_hint)
468 #endif
469 #ifndef OPENSSL_NO_SRP
470                             /* SRP: send ServerKeyExchange */
471                             || (alg_k & SSL_kSRP)
472 #endif
473                             || (alg_k & (SSL_kDHr|SSL_kDHd|SSL_kEDH))
474                             || (alg_k & SSL_kEECDH)
475                             || ((alg_k & SSL_kRSA)
476                                 && (s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey == NULL
477                                     || (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher)
478                                         && EVP_PKEY_size(s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey)*8 > SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher)
479                                         )
480                                     )
481                                 )
482                             )
483                                 {
484                                 ret=ssl3_send_server_key_exchange(s);
485                                 if (ret <= 0) goto end;
486                                 }
487                         else
488                                 skip=1;
489
490                         s->state=SSL3_ST_SW_CERT_REQ_A;
491                         s->init_num=0;
492                         break;
493
494                 case SSL3_ST_SW_CERT_REQ_A:
495                 case SSL3_ST_SW_CERT_REQ_B:
496                         if (/* don't request cert unless asked for it: */
497                                 !(s->verify_mode & SSL_VERIFY_PEER) ||
498                                 /* if SSL_VERIFY_CLIENT_ONCE is set,
499                                  * don't request cert during re-negotiation: */
500                                 ((s->session->peer != NULL) &&
501                                  (s->verify_mode & SSL_VERIFY_CLIENT_ONCE)) ||
502                                 /* never request cert in anonymous ciphersuites
503                                  * (see section "Certificate request" in SSL 3 drafts
504                                  * and in RFC 2246): */
505                                 ((s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL) &&
506                                  /* ... except when the application insists on verification
507                                   * (against the specs, but s3_clnt.c accepts this for SSL 3) */
508                                  !(s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT)) ||
509                                  /* never request cert in Kerberos ciphersuites */
510                                 (s->s3->tmp.new_cipher->algorithm_auth & SSL_aKRB5)
511                                 /* With normal PSK Certificates and
512                                  * Certificate Requests are omitted */
513                                 || (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
514                                 {
515                                 /* no cert request */
516                                 skip=1;
517                                 s->s3->tmp.cert_request=0;
518                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
519                                 if (s->s3->handshake_buffer)
520                                         if (!ssl3_digest_cached_records(s))
521                                                 return -1;
522                                 }
523                         else
524                                 {
525                                 s->s3->tmp.cert_request=1;
526                                 ret=ssl3_send_certificate_request(s);
527                                 if (ret <= 0) goto end;
528 #ifndef NETSCAPE_HANG_BUG
529                                 s->state=SSL3_ST_SW_SRVR_DONE_A;
530 #else
531                                 s->state=SSL3_ST_SW_FLUSH;
532                                 s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
533 #endif
534                                 s->init_num=0;
535                                 }
536                         break;
537
538                 case SSL3_ST_SW_SRVR_DONE_A:
539                 case SSL3_ST_SW_SRVR_DONE_B:
540                         ret=ssl3_send_server_done(s);
541                         if (ret <= 0) goto end;
542                         s->s3->tmp.next_state=SSL3_ST_SR_CERT_A;
543                         s->state=SSL3_ST_SW_FLUSH;
544                         s->init_num=0;
545                         break;
546                 
547                 case SSL3_ST_SW_FLUSH:
548
549                         /* This code originally checked to see if
550                          * any data was pending using BIO_CTRL_INFO
551                          * and then flushed. This caused problems
552                          * as documented in PR#1939. The proposed
553                          * fix doesn't completely resolve this issue
554                          * as buggy implementations of BIO_CTRL_PENDING
555                          * still exist. So instead we just flush
556                          * unconditionally.
557                          */
558
559                         s->rwstate=SSL_WRITING;
560                         if (BIO_flush(s->wbio) <= 0)
561                                 {
562                                 ret= -1;
563                                 goto end;
564                                 }
565                         s->rwstate=SSL_NOTHING;
566
567                         s->state=s->s3->tmp.next_state;
568                         break;
569
570                 case SSL3_ST_SR_CERT_A:
571                 case SSL3_ST_SR_CERT_B:
572                         /* Check for second client hello (MS SGC) */
573                         ret = ssl3_check_client_hello(s);
574                         if (ret <= 0)
575                                 goto end;
576                         if (ret == 2)
577                                 s->state = SSL3_ST_SR_CLNT_HELLO_C;
578                         else {
579                                 if (s->s3->tmp.cert_request)
580                                         {
581                                         ret=ssl3_get_client_certificate(s);
582                                         if (ret <= 0) goto end;
583                                         }
584                                 s->init_num=0;
585                                 s->state=SSL3_ST_SR_KEY_EXCH_A;
586                         }
587                         break;
588
589                 case SSL3_ST_SR_KEY_EXCH_A:
590                 case SSL3_ST_SR_KEY_EXCH_B:
591                         ret=ssl3_get_client_key_exchange(s);
592                         if (ret <= 0)
593                                 goto end;
594                         if (ret == 2)
595                                 {
596                                 /* For the ECDH ciphersuites when
597                                  * the client sends its ECDH pub key in
598                                  * a certificate, the CertificateVerify
599                                  * message is not sent.
600                                  * Also for GOST ciphersuites when
601                                  * the client uses its key from the certificate
602                                  * for key exchange.
603                                  */
604 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
605                                 s->state=SSL3_ST_SR_FINISHED_A;
606 #else
607                                 if (s->s3->next_proto_neg_seen)
608                                         s->state=SSL3_ST_SR_NEXT_PROTO_A;
609                                 else
610                                         s->state=SSL3_ST_SR_FINISHED_A;
611 #endif
612                                 s->init_num = 0;
613                                 }
614                         else if (TLS1_get_version(s) >= TLS1_2_VERSION)
615                                 {
616                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
617                                 s->init_num=0;
618                                 if (!s->session->peer)
619                                         break;
620                                 /* For TLS v1.2 freeze the handshake buffer
621                                  * at this point and digest cached records.
622                                  */
623                                 if (!s->s3->handshake_buffer)
624                                         {
625                                         SSLerr(SSL_F_SSL3_ACCEPT,ERR_R_INTERNAL_ERROR);
626                                         return -1;
627                                         }
628                                 s->s3->flags |= TLS1_FLAGS_KEEP_HANDSHAKE;
629                                 if (!ssl3_digest_cached_records(s))
630                                         return -1;
631                                 }
632                         else
633                                 {
634                                 int offset=0;
635                                 int dgst_num;
636
637                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
638                                 s->init_num=0;
639
640                                 /* We need to get hashes here so if there is
641                                  * a client cert, it can be verified
642                                  * FIXME - digest processing for CertificateVerify
643                                  * should be generalized. But it is next step
644                                  */
645                                 if (s->s3->handshake_buffer)
646                                         if (!ssl3_digest_cached_records(s))
647                                                 return -1;
648                                 for (dgst_num=0; dgst_num<SSL_MAX_DIGEST;dgst_num++)    
649                                         if (s->s3->handshake_dgst[dgst_num]) 
650                                                 {
651                                                 int dgst_size;
652
653                                                 s->method->ssl3_enc->cert_verify_mac(s,EVP_MD_CTX_type(s->s3->handshake_dgst[dgst_num]),&(s->s3->tmp.cert_verify_md[offset]));
654                                                 dgst_size=EVP_MD_CTX_size(s->s3->handshake_dgst[dgst_num]);
655                                                 if (dgst_size < 0)
656                                                         {
657                                                         ret = -1;
658                                                         goto end;
659                                                         }
660                                                 offset+=dgst_size;
661                                                 }               
662                                 }
663                         break;
664
665                 case SSL3_ST_SR_CERT_VRFY_A:
666                 case SSL3_ST_SR_CERT_VRFY_B:
667
668                         /* we should decide if we expected this one */
669                         ret=ssl3_get_cert_verify(s);
670                         if (ret <= 0) goto end;
671
672 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
673                         s->state=SSL3_ST_SR_FINISHED_A;
674 #else
675                         if (s->s3->next_proto_neg_seen)
676                                 s->state=SSL3_ST_SR_NEXT_PROTO_A;
677                         else
678                                 s->state=SSL3_ST_SR_FINISHED_A;
679 #endif
680                         s->init_num=0;
681                         break;
682
683 #if !defined(OPENSSL_NO_TLSEXT) && !defined(OPENSSL_NO_NEXTPROTONEG)
684                 case SSL3_ST_SR_NEXT_PROTO_A:
685                 case SSL3_ST_SR_NEXT_PROTO_B:
686                         ret=ssl3_get_next_proto(s);
687                         if (ret <= 0) goto end;
688                         s->init_num = 0;
689                         s->state=SSL3_ST_SR_FINISHED_A;
690                         break;
691 #endif
692
693                 case SSL3_ST_SR_FINISHED_A:
694                 case SSL3_ST_SR_FINISHED_B:
695                         ret=ssl3_get_finished(s,SSL3_ST_SR_FINISHED_A,
696                                 SSL3_ST_SR_FINISHED_B);
697                         if (ret <= 0) goto end;
698                         if (s->hit)
699                                 s->state=SSL_ST_OK;
700 #ifndef OPENSSL_NO_TLSEXT
701                         else if (s->tlsext_ticket_expected)
702                                 s->state=SSL3_ST_SW_SESSION_TICKET_A;
703 #endif
704                         else
705                                 s->state=SSL3_ST_SW_CHANGE_A;
706                         s->init_num=0;
707                         break;
708
709 #ifndef OPENSSL_NO_TLSEXT
710                 case SSL3_ST_SW_SESSION_TICKET_A:
711                 case SSL3_ST_SW_SESSION_TICKET_B:
712                         ret=ssl3_send_newsession_ticket(s);
713                         if (ret <= 0) goto end;
714                         s->state=SSL3_ST_SW_CHANGE_A;
715                         s->init_num=0;
716                         break;
717
718                 case SSL3_ST_SW_CERT_STATUS_A:
719                 case SSL3_ST_SW_CERT_STATUS_B:
720                         ret=ssl3_send_cert_status(s);
721                         if (ret <= 0) goto end;
722                         s->state=SSL3_ST_SW_KEY_EXCH_A;
723                         s->init_num=0;
724                         break;
725
726 #endif
727
728                 case SSL3_ST_SW_CHANGE_A:
729                 case SSL3_ST_SW_CHANGE_B:
730
731                         s->session->cipher=s->s3->tmp.new_cipher;
732                         if (!s->method->ssl3_enc->setup_key_block(s))
733                                 { ret= -1; goto end; }
734
735                         ret=ssl3_send_change_cipher_spec(s,
736                                 SSL3_ST_SW_CHANGE_A,SSL3_ST_SW_CHANGE_B);
737
738                         if (ret <= 0) goto end;
739                         s->state=SSL3_ST_SW_FINISHED_A;
740                         s->init_num=0;
741
742                         if (!s->method->ssl3_enc->change_cipher_state(s,
743                                 SSL3_CHANGE_CIPHER_SERVER_WRITE))
744                                 {
745                                 ret= -1;
746                                 goto end;
747                                 }
748
749                         break;
750
751                 case SSL3_ST_SW_FINISHED_A:
752                 case SSL3_ST_SW_FINISHED_B:
753                         ret=ssl3_send_finished(s,
754                                 SSL3_ST_SW_FINISHED_A,SSL3_ST_SW_FINISHED_B,
755                                 s->method->ssl3_enc->server_finished_label,
756                                 s->method->ssl3_enc->server_finished_label_len);
757                         if (ret <= 0) goto end;
758                         s->state=SSL3_ST_SW_FLUSH;
759                         if (s->hit)
760                                 {
761 #if defined(OPENSSL_NO_TLSEXT) || defined(OPENSSL_NO_NEXTPROTONEG)
762                                 s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
763 #else
764                                 if (s->s3->next_proto_neg_seen)
765                                         s->s3->tmp.next_state=SSL3_ST_SR_NEXT_PROTO_A;
766                                 else
767                                         s->s3->tmp.next_state=SSL3_ST_SR_FINISHED_A;
768 #endif
769                                 }
770                         else
771                                 s->s3->tmp.next_state=SSL_ST_OK;
772                         s->init_num=0;
773                         break;
774
775                 case SSL_ST_OK:
776                         /* clean a few things up */
777                         ssl3_cleanup_key_block(s);
778
779                         BUF_MEM_free(s->init_buf);
780                         s->init_buf=NULL;
781
782                         /* remove buffering on output */
783                         ssl_free_wbio_buffer(s);
784
785                         s->init_num=0;
786
787                         if (s->renegotiate == 2) /* skipped if we just sent a HelloRequest */
788                                 {
789                                 s->renegotiate=0;
790                                 s->new_session=0;
791                                 
792                                 ssl_update_cache(s,SSL_SESS_CACHE_SERVER);
793                                 
794                                 s->ctx->stats.sess_accept_good++;
795                                 /* s->server=1; */
796                                 s->handshake_func=ssl3_accept;
797
798                                 if (cb != NULL) cb(s,SSL_CB_HANDSHAKE_DONE,1);
799                                 }
800                         
801                         ret = 1;
802                         goto end;
803                         /* break; */
804
805                 default:
806                         SSLerr(SSL_F_SSL3_ACCEPT,SSL_R_UNKNOWN_STATE);
807                         ret= -1;
808                         goto end;
809                         /* break; */
810                         }
811                 
812                 if (!s->s3->tmp.reuse_message && !skip)
813                         {
814                         if (s->debug)
815                                 {
816                                 if ((ret=BIO_flush(s->wbio)) <= 0)
817                                         goto end;
818                                 }
819
820
821                         if ((cb != NULL) && (s->state != state))
822                                 {
823                                 new_state=s->state;
824                                 s->state=state;
825                                 cb(s,SSL_CB_ACCEPT_LOOP,1);
826                                 s->state=new_state;
827                                 }
828                         }
829                 skip=0;
830                 }
831 end:
832         /* BIO_flush(s->wbio); */
833
834         s->in_handshake--;
835         if (cb != NULL)
836                 cb(s,SSL_CB_ACCEPT_EXIT,ret);
837         return(ret);
838         }
839
840 int ssl3_send_hello_request(SSL *s)
841         {
842         unsigned char *p;
843
844         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
845                 {
846                 p=(unsigned char *)s->init_buf->data;
847                 *(p++)=SSL3_MT_HELLO_REQUEST;
848                 *(p++)=0;
849                 *(p++)=0;
850                 *(p++)=0;
851
852                 s->state=SSL3_ST_SW_HELLO_REQ_B;
853                 /* number of bytes to write */
854                 s->init_num=4;
855                 s->init_off=0;
856                 }
857
858         /* SSL3_ST_SW_HELLO_REQ_B */
859         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
860         }
861
862 int ssl3_check_client_hello(SSL *s)
863         {
864         int ok;
865         long n;
866
867         /* this function is called when we really expect a Certificate message,
868          * so permit appropriate message length */
869         n=s->method->ssl_get_message(s,
870                 SSL3_ST_SR_CERT_A,
871                 SSL3_ST_SR_CERT_B,
872                 -1,
873                 s->max_cert_list,
874                 &ok);
875         if (!ok) return((int)n);
876         s->s3->tmp.reuse_message = 1;
877         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
878                 {
879                 /* Throw away what we have done so far in the current handshake,
880                  * which will now be aborted. (A full SSL_clear would be too much.) */
881 #ifndef OPENSSL_NO_DH
882                 if (s->s3->tmp.dh != NULL)
883                         {
884                         DH_free(s->s3->tmp.dh);
885                         s->s3->tmp.dh = NULL;
886                         }
887 #endif
888 #ifndef OPENSSL_NO_ECDH
889                 if (s->s3->tmp.ecdh != NULL)
890                         {
891                         EC_KEY_free(s->s3->tmp.ecdh);
892                         s->s3->tmp.ecdh = NULL;
893                         }
894 #endif
895                 return 2;
896                 }
897         return 1;
898 }
899
900 int ssl3_get_client_hello(SSL *s)
901         {
902         int i,j,ok,al,ret= -1;
903         unsigned int cookie_len;
904         long n;
905         unsigned long id;
906         unsigned char *p,*d,*q;
907         SSL_CIPHER *c;
908 #ifndef OPENSSL_NO_COMP
909         SSL_COMP *comp=NULL;
910 #endif
911         STACK_OF(SSL_CIPHER) *ciphers=NULL;
912
913         /* We do this so that we will respond with our native type.
914          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
915          * This down switching should be handled by a different method.
916          * If we are SSLv3, we will respond with SSLv3, even if prompted with
917          * TLSv1.
918          */
919         if (s->state == SSL3_ST_SR_CLNT_HELLO_A
920 #ifndef OPENSSL_NO_SRP
921                 || (s->state == SSL3_ST_SR_CLNT_HELLO_SRP_USERNAME)
922 #endif
923                 )
924                 {
925                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
926                 }
927         s->first_packet=1;
928         n=s->method->ssl_get_message(s,
929                 SSL3_ST_SR_CLNT_HELLO_B,
930                 SSL3_ST_SR_CLNT_HELLO_C,
931                 SSL3_MT_CLIENT_HELLO,
932                 SSL3_RT_MAX_PLAIN_LENGTH,
933                 &ok);
934
935         if (!ok) return((int)n);
936         s->first_packet=0;
937         d=p=(unsigned char *)s->init_msg;
938
939         /* use version from inside client hello, not from record header
940          * (may differ: see RFC 2246, Appendix E, second paragraph) */
941         s->client_version=(((int)p[0])<<8)|(int)p[1];
942         p+=2;
943
944         if ((s->version == DTLS1_VERSION && s->client_version > s->version) ||
945             (s->version != DTLS1_VERSION && s->client_version < s->version))
946                 {
947                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
948                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR)
949                         {
950                         /* similar to ssl3_get_record, send alert using remote version number */
951                         s->version = s->client_version;
952                         }
953                 al = SSL_AD_PROTOCOL_VERSION;
954                 goto f_err;
955                 }
956
957         /* If we require cookies and this ClientHello doesn't
958          * contain one, just return since we do not want to
959          * allocate any memory yet. So check cookie length...
960          */
961         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
962                 {
963                 unsigned int session_length, cookie_length;
964                 
965                 session_length = *(p + SSL3_RANDOM_SIZE);
966                 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
967
968                 if (cookie_length == 0)
969                         return 1;
970                 }
971
972         /* load the client random */
973         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
974         p+=SSL3_RANDOM_SIZE;
975
976         /* get the session-id */
977         j= *(p++);
978
979         s->hit=0;
980         /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
981          * 0.9.7 and later allow this by default, but optionally ignore resumption requests
982          * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
983          * than a change to default behavior so that applications relying on this for security
984          * won't even compile against older library versions).
985          *
986          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
987          * renegotiation but not a new session (s->new_session remains unset): for servers,
988          * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
989          * setting will be ignored.
990          */
991         if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
992                 {
993                 if (!ssl_get_new_session(s,1))
994                         goto err;
995                 }
996         else
997                 {
998                 i=ssl_get_prev_session(s, p, j, d + n);
999                 if (i == 1)
1000                         { /* previous session */
1001                         s->hit=1;
1002                         }
1003                 else if (i == -1)
1004                         goto err;
1005                 else /* i == 0 */
1006                         {
1007                         if (!ssl_get_new_session(s,1))
1008                                 goto err;
1009                         }
1010                 }
1011
1012         p+=j;
1013
1014         if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER)
1015                 {
1016                 /* cookie stuff */
1017                 cookie_len = *(p++);
1018
1019                 /* 
1020                  * The ClientHello may contain a cookie even if the
1021                  * HelloVerify message has not been sent--make sure that it
1022                  * does not cause an overflow.
1023                  */
1024                 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1025                         {
1026                         /* too much data */
1027                         al = SSL_AD_DECODE_ERROR;
1028                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1029                         goto f_err;
1030                         }
1031
1032                 /* verify the cookie if appropriate option is set. */
1033                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1034                         cookie_len > 0)
1035                         {
1036                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
1037
1038                         if ( s->ctx->app_verify_cookie_cb != NULL)
1039                                 {
1040                                 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1041                                         cookie_len) == 0)
1042                                         {
1043                                         al=SSL_AD_HANDSHAKE_FAILURE;
1044                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1045                                                 SSL_R_COOKIE_MISMATCH);
1046                                         goto f_err;
1047                                         }
1048                                 /* else cookie verification succeeded */
1049                                 }
1050                         else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, 
1051                                                   s->d1->cookie_len) != 0) /* default verification */
1052                                 {
1053                                         al=SSL_AD_HANDSHAKE_FAILURE;
1054                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1055                                                 SSL_R_COOKIE_MISMATCH);
1056                                         goto f_err;
1057                                 }
1058
1059                         ret = 2;
1060                         }
1061
1062                 p += cookie_len;
1063                 }
1064
1065         n2s(p,i);
1066         if ((i == 0) && (j != 0))
1067                 {
1068                 /* we need a cipher if we are not resuming a session */
1069                 al=SSL_AD_ILLEGAL_PARAMETER;
1070                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1071                 goto f_err;
1072                 }
1073         if ((p+i) >= (d+n))
1074                 {
1075                 /* not enough data */
1076                 al=SSL_AD_DECODE_ERROR;
1077                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1078                 goto f_err;
1079                 }
1080         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1081                 == NULL))
1082                 {
1083                 goto err;
1084                 }
1085         p+=i;
1086
1087         /* If it is a hit, check that the cipher is in the list */
1088         if ((s->hit) && (i > 0))
1089                 {
1090                 j=0;
1091                 id=s->session->cipher->id;
1092
1093 #ifdef CIPHER_DEBUG
1094                 printf("client sent %d ciphers\n",sk_num(ciphers));
1095 #endif
1096                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1097                         {
1098                         c=sk_SSL_CIPHER_value(ciphers,i);
1099 #ifdef CIPHER_DEBUG
1100                         printf("client [%2d of %2d]:%s\n",
1101                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
1102 #endif
1103                         if (c->id == id)
1104                                 {
1105                                 j=1;
1106                                 break;
1107                                 }
1108                         }
1109 /* Disabled because it can be used in a ciphersuite downgrade
1110  * attack: CVE-2010-4180.
1111  */
1112 #if 0
1113                 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1114                         {
1115                         /* Special case as client bug workaround: the previously used cipher may
1116                          * not be in the current list, the client instead might be trying to
1117                          * continue using a cipher that before wasn't chosen due to server
1118                          * preferences.  We'll have to reject the connection if the cipher is not
1119                          * enabled, though. */
1120                         c = sk_SSL_CIPHER_value(ciphers, 0);
1121                         if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1122                                 {
1123                                 s->session->cipher = c;
1124                                 j = 1;
1125                                 }
1126                         }
1127 #endif
1128                 if (j == 0)
1129                         {
1130                         /* we need to have the cipher in the cipher
1131                          * list if we are asked to reuse it */
1132                         al=SSL_AD_ILLEGAL_PARAMETER;
1133                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1134                         goto f_err;
1135                         }
1136                 }
1137
1138         /* compression */
1139         i= *(p++);
1140         if ((p+i) > (d+n))
1141                 {
1142                 /* not enough data */
1143                 al=SSL_AD_DECODE_ERROR;
1144                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1145                 goto f_err;
1146                 }
1147         q=p;
1148         for (j=0; j<i; j++)
1149                 {
1150                 if (p[j] == 0) break;
1151                 }
1152
1153         p+=i;
1154         if (j >= i)
1155                 {
1156                 /* no compress */
1157                 al=SSL_AD_DECODE_ERROR;
1158                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1159                 goto f_err;
1160                 }
1161
1162 #ifndef OPENSSL_NO_TLSEXT
1163         /* TLS extensions*/
1164         if (s->version >= SSL3_VERSION)
1165                 {
1166                 if (!ssl_parse_clienthello_tlsext(s,&p,d,n, &al))
1167                         {
1168                         /* 'al' set by ssl_parse_clienthello_tlsext */
1169                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1170                         goto f_err;
1171                         }
1172                 }
1173                 if (ssl_check_clienthello_tlsext(s) <= 0) {
1174                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CLIENTHELLO_TLSEXT);
1175                         goto err;
1176                 }
1177
1178         /* Check if we want to use external pre-shared secret for this
1179          * handshake for not reused session only. We need to generate
1180          * server_random before calling tls_session_secret_cb in order to allow
1181          * SessionTicket processing to use it in key derivation. */
1182         {
1183                 unsigned long Time;
1184                 unsigned char *pos;
1185                 Time=(unsigned long)time(NULL);                 /* Time */
1186                 pos=s->s3->server_random;
1187                 l2n(Time,pos);
1188                 if (RAND_pseudo_bytes(pos,SSL3_RANDOM_SIZE-4) <= 0)
1189                         {
1190                         al=SSL_AD_INTERNAL_ERROR;
1191                         goto f_err;
1192                         }
1193         }
1194
1195         if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1196                 {
1197                 SSL_CIPHER *pref_cipher=NULL;
1198
1199                 s->session->master_key_length=sizeof(s->session->master_key);
1200                 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1201                         ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1202                         {
1203                         s->hit=1;
1204                         s->session->ciphers=ciphers;
1205                         s->session->verify_result=X509_V_OK;
1206
1207                         ciphers=NULL;
1208
1209                         /* check if some cipher was preferred by call back */
1210                         pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1211                         if (pref_cipher == NULL)
1212                                 {
1213                                 al=SSL_AD_HANDSHAKE_FAILURE;
1214                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1215                                 goto f_err;
1216                                 }
1217
1218                         s->session->cipher=pref_cipher;
1219
1220                         if (s->cipher_list)
1221                                 sk_SSL_CIPHER_free(s->cipher_list);
1222
1223                         if (s->cipher_list_by_id)
1224                                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1225
1226                         s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1227                         s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1228                         }
1229                 }
1230 #endif
1231
1232         /* Worst case, we will use the NULL compression, but if we have other
1233          * options, we will now look for them.  We have i-1 compression
1234          * algorithms from the client, starting at q. */
1235         s->s3->tmp.new_compression=NULL;
1236 #ifndef OPENSSL_NO_COMP
1237         /* This only happens if we have a cache hit */
1238         if (s->session->compress_meth != 0)
1239                 {
1240                 int m, comp_id = s->session->compress_meth;
1241                 /* Perform sanity checks on resumed compression algorithm */
1242                 /* Can't disable compression */
1243                 if (s->options & SSL_OP_NO_COMPRESSION)
1244                         {
1245                         al=SSL_AD_INTERNAL_ERROR;
1246                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1247                         goto f_err;
1248                         }
1249                 /* Look for resumed compression method */
1250                 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1251                         {
1252                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1253                         if (comp_id == comp->id)
1254                                 {
1255                                 s->s3->tmp.new_compression=comp;
1256                                 break;
1257                                 }
1258                         }
1259                 if (s->s3->tmp.new_compression == NULL)
1260                         {
1261                         al=SSL_AD_INTERNAL_ERROR;
1262                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1263                         goto f_err;
1264                         }
1265                 /* Look for resumed method in compression list */
1266                 for (m = 0; m < i; m++)
1267                         {
1268                         if (q[m] == comp_id)
1269                                 break;
1270                         }
1271                 if (m >= i)
1272                         {
1273                         al=SSL_AD_ILLEGAL_PARAMETER;
1274                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1275                         goto f_err;
1276                         }
1277                 }
1278         else if (s->hit)
1279                 comp = NULL;
1280         else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
1281                 { /* See if we have a match */
1282                 int m,nn,o,v,done=0;
1283
1284                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1285                 for (m=0; m<nn; m++)
1286                         {
1287                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1288                         v=comp->id;
1289                         for (o=0; o<i; o++)
1290                                 {
1291                                 if (v == q[o])
1292                                         {
1293                                         done=1;
1294                                         break;
1295                                         }
1296                                 }
1297                         if (done) break;
1298                         }
1299                 if (done)
1300                         s->s3->tmp.new_compression=comp;
1301                 else
1302                         comp=NULL;
1303                 }
1304 #else
1305         /* If compression is disabled we'd better not try to resume a session
1306          * using compression.
1307          */
1308         if (s->session->compress_meth != 0)
1309                 {
1310                 al=SSL_AD_INTERNAL_ERROR;
1311                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1312                 goto f_err;
1313                 }
1314 #endif
1315
1316         /* Given s->session->ciphers and SSL_get_ciphers, we must
1317          * pick a cipher */
1318
1319         if (!s->hit)
1320                 {
1321 #ifdef OPENSSL_NO_COMP
1322                 s->session->compress_meth=0;
1323 #else
1324                 s->session->compress_meth=(comp == NULL)?0:comp->id;
1325 #endif
1326                 if (s->session->ciphers != NULL)
1327                         sk_SSL_CIPHER_free(s->session->ciphers);
1328                 s->session->ciphers=ciphers;
1329                 if (ciphers == NULL)
1330                         {
1331                         al=SSL_AD_ILLEGAL_PARAMETER;
1332                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1333                         goto f_err;
1334                         }
1335                 ciphers=NULL;
1336                 c=ssl3_choose_cipher(s,s->session->ciphers,
1337                                      SSL_get_ciphers(s));
1338
1339                 if (c == NULL)
1340                         {
1341                         al=SSL_AD_HANDSHAKE_FAILURE;
1342                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1343                         goto f_err;
1344                         }
1345                 s->s3->tmp.new_cipher=c;
1346                 /* check whether we should disable session resumption */
1347                 if (s->not_resumable_session_cb != NULL)
1348                         s->session->not_resumable=s->not_resumable_session_cb(s,
1349                                 ((c->algorithm_mkey & (SSL_kEDH | SSL_kEECDH)) != 0));
1350                 if (s->session->not_resumable)
1351                         /* do not send a session ticket */
1352                         s->tlsext_ticket_expected = 0;
1353                 }
1354         else
1355                 {
1356                 /* Session-id reuse */
1357 #ifdef REUSE_CIPHER_BUG
1358                 STACK_OF(SSL_CIPHER) *sk;
1359                 SSL_CIPHER *nc=NULL;
1360                 SSL_CIPHER *ec=NULL;
1361
1362                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1363                         {
1364                         sk=s->session->ciphers;
1365                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1366                                 {
1367                                 c=sk_SSL_CIPHER_value(sk,i);
1368                                 if (c->algorithm_enc & SSL_eNULL)
1369                                         nc=c;
1370                                 if (SSL_C_IS_EXPORT(c))
1371                                         ec=c;
1372                                 }
1373                         if (nc != NULL)
1374                                 s->s3->tmp.new_cipher=nc;
1375                         else if (ec != NULL)
1376                                 s->s3->tmp.new_cipher=ec;
1377                         else
1378                                 s->s3->tmp.new_cipher=s->session->cipher;
1379                         }
1380                 else
1381 #endif
1382                 s->s3->tmp.new_cipher=s->session->cipher;
1383                 }
1384
1385         if (TLS1_get_version(s) < TLS1_2_VERSION || !(s->verify_mode & SSL_VERIFY_PEER))
1386                 {
1387                 if (!ssl3_digest_cached_records(s))
1388                         goto f_err;
1389                 }
1390         
1391         /* we now have the following setup. 
1392          * client_random
1393          * cipher_list          - our prefered list of ciphers
1394          * ciphers              - the clients prefered list of ciphers
1395          * compression          - basically ignored right now
1396          * ssl version is set   - sslv3
1397          * s->session           - The ssl session has been setup.
1398          * s->hit               - session reuse flag
1399          * s->tmp.new_cipher    - the new cipher to use.
1400          */
1401
1402         if (ret < 0) ret=1;
1403         if (0)
1404                 {
1405 f_err:
1406                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1407                 }
1408 err:
1409         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1410         return(ret);
1411         }
1412
1413 int ssl3_send_server_hello(SSL *s)
1414         {
1415         unsigned char *buf;
1416         unsigned char *p,*d;
1417         int i,sl;
1418         unsigned long l;
1419 #ifdef OPENSSL_NO_TLSEXT
1420         unsigned long Time;
1421 #endif
1422
1423         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1424                 {
1425                 buf=(unsigned char *)s->init_buf->data;
1426 #ifdef OPENSSL_NO_TLSEXT
1427                 p=s->s3->server_random;
1428                 /* Generate server_random if it was not needed previously */
1429                 Time=(unsigned long)time(NULL);                 /* Time */
1430                 l2n(Time,p);
1431                 if (RAND_pseudo_bytes(p,SSL3_RANDOM_SIZE-4) <= 0)
1432                         return -1;
1433 #endif
1434                 /* Do the message type and length last */
1435                 d=p= &(buf[4]);
1436
1437                 *(p++)=s->version>>8;
1438                 *(p++)=s->version&0xff;
1439
1440                 /* Random stuff */
1441                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1442                 p+=SSL3_RANDOM_SIZE;
1443
1444                 /* There are several cases for the session ID to send
1445                  * back in the server hello:
1446                  * - For session reuse from the session cache,
1447                  *   we send back the old session ID.
1448                  * - If stateless session reuse (using a session ticket)
1449                  *   is successful, we send back the client's "session ID"
1450                  *   (which doesn't actually identify the session).
1451                  * - If it is a new session, we send back the new
1452                  *   session ID.
1453                  * - However, if we want the new session to be single-use,
1454                  *   we send back a 0-length session ID.
1455                  * s->hit is non-zero in either case of session reuse,
1456                  * so the following won't overwrite an ID that we're supposed
1457                  * to send back.
1458                  */
1459                 if (s->session->not_resumable ||
1460                         (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1461                                 && !s->hit))
1462                         s->session->session_id_length=0;
1463
1464                 sl=s->session->session_id_length;
1465                 if (sl > (int)sizeof(s->session->session_id))
1466                         {
1467                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1468                         return -1;
1469                         }
1470                 *(p++)=sl;
1471                 memcpy(p,s->session->session_id,sl);
1472                 p+=sl;
1473
1474                 /* put the cipher */
1475                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1476                 p+=i;
1477
1478                 /* put the compression method */
1479 #ifdef OPENSSL_NO_COMP
1480                         *(p++)=0;
1481 #else
1482                 if (s->s3->tmp.new_compression == NULL)
1483                         *(p++)=0;
1484                 else
1485                         *(p++)=s->s3->tmp.new_compression->id;
1486 #endif
1487 #ifndef OPENSSL_NO_TLSEXT
1488                 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1489                         {
1490                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1491                         return -1;
1492                         }
1493                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH)) == NULL)
1494                         {
1495                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1496                         return -1;
1497                         }
1498 #endif
1499                 /* do the header */
1500                 l=(p-d);
1501                 d=buf;
1502                 *(d++)=SSL3_MT_SERVER_HELLO;
1503                 l2n3(l,d);
1504
1505                 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1506                 /* number of bytes to write */
1507                 s->init_num=p-buf;
1508                 s->init_off=0;
1509                 }
1510
1511         /* SSL3_ST_SW_SRVR_HELLO_B */
1512         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1513         }
1514
1515 int ssl3_send_server_done(SSL *s)
1516         {
1517         unsigned char *p;
1518
1519         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1520                 {
1521                 p=(unsigned char *)s->init_buf->data;
1522
1523                 /* do the header */
1524                 *(p++)=SSL3_MT_SERVER_DONE;
1525                 *(p++)=0;
1526                 *(p++)=0;
1527                 *(p++)=0;
1528
1529                 s->state=SSL3_ST_SW_SRVR_DONE_B;
1530                 /* number of bytes to write */
1531                 s->init_num=4;
1532                 s->init_off=0;
1533                 }
1534
1535         /* SSL3_ST_SW_SRVR_DONE_B */
1536         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
1537         }
1538
1539 int ssl3_send_server_key_exchange(SSL *s)
1540         {
1541 #ifndef OPENSSL_NO_RSA
1542         unsigned char *q;
1543         int j,num;
1544         RSA *rsa;
1545         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1546         unsigned int u;
1547 #endif
1548 #ifndef OPENSSL_NO_DH
1549         DH *dh=NULL,*dhp;
1550 #endif
1551 #ifndef OPENSSL_NO_ECDH
1552         EC_KEY *ecdh=NULL, *ecdhp;
1553         unsigned char *encodedPoint = NULL;
1554         int encodedlen = 0;
1555         int curve_id = 0;
1556         BN_CTX *bn_ctx = NULL; 
1557 #endif
1558         EVP_PKEY *pkey;
1559         const EVP_MD *md = NULL;
1560         unsigned char *p,*d;
1561         int al,i;
1562         unsigned long type;
1563         int n;
1564         CERT *cert;
1565         BIGNUM *r[4];
1566         int nr[4],kn;
1567         BUF_MEM *buf;
1568         EVP_MD_CTX md_ctx;
1569
1570         EVP_MD_CTX_init(&md_ctx);
1571         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1572                 {
1573                 type=s->s3->tmp.new_cipher->algorithm_mkey;
1574                 cert=s->cert;
1575
1576                 buf=s->init_buf;
1577
1578                 r[0]=r[1]=r[2]=r[3]=NULL;
1579                 n=0;
1580 #ifndef OPENSSL_NO_RSA
1581                 if (type & SSL_kRSA)
1582                         {
1583                         rsa=cert->rsa_tmp;
1584                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1585                                 {
1586                                 rsa=s->cert->rsa_tmp_cb(s,
1587                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1588                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1589                                 if(rsa == NULL)
1590                                 {
1591                                         al=SSL_AD_HANDSHAKE_FAILURE;
1592                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1593                                         goto f_err;
1594                                 }
1595                                 RSA_up_ref(rsa);
1596                                 cert->rsa_tmp=rsa;
1597                                 }
1598                         if (rsa == NULL)
1599                                 {
1600                                 al=SSL_AD_HANDSHAKE_FAILURE;
1601                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1602                                 goto f_err;
1603                                 }
1604                         r[0]=rsa->n;
1605                         r[1]=rsa->e;
1606                         s->s3->tmp.use_rsa_tmp=1;
1607                         }
1608                 else
1609 #endif
1610 #ifndef OPENSSL_NO_DH
1611                         if (type & SSL_kEDH)
1612                         {
1613                         dhp=cert->dh_tmp;
1614                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1615                                 dhp=s->cert->dh_tmp_cb(s,
1616                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1617                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1618                         if (dhp == NULL)
1619                                 {
1620                                 al=SSL_AD_HANDSHAKE_FAILURE;
1621                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1622                                 goto f_err;
1623                                 }
1624
1625                         if (s->s3->tmp.dh != NULL)
1626                                 {
1627                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1628                                 goto err;
1629                                 }
1630
1631                         if ((dh=DHparams_dup(dhp)) == NULL)
1632                                 {
1633                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1634                                 goto err;
1635                                 }
1636
1637                         s->s3->tmp.dh=dh;
1638                         if ((dhp->pub_key == NULL ||
1639                              dhp->priv_key == NULL ||
1640                              (s->options & SSL_OP_SINGLE_DH_USE)))
1641                                 {
1642                                 if(!DH_generate_key(dh))
1643                                     {
1644                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1645                                            ERR_R_DH_LIB);
1646                                     goto err;
1647                                     }
1648                                 }
1649                         else
1650                                 {
1651                                 dh->pub_key=BN_dup(dhp->pub_key);
1652                                 dh->priv_key=BN_dup(dhp->priv_key);
1653                                 if ((dh->pub_key == NULL) ||
1654                                         (dh->priv_key == NULL))
1655                                         {
1656                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1657                                         goto err;
1658                                         }
1659                                 }
1660                         r[0]=dh->p;
1661                         r[1]=dh->g;
1662                         r[2]=dh->pub_key;
1663                         }
1664                 else 
1665 #endif
1666 #ifndef OPENSSL_NO_ECDH
1667                         if (type & SSL_kEECDH)
1668                         {
1669                         const EC_GROUP *group;
1670
1671                         ecdhp=cert->ecdh_tmp;
1672                         if ((ecdhp == NULL) && (s->cert->ecdh_tmp_cb != NULL))
1673                                 {
1674                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1675                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1676                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1677                                 }
1678                         if (ecdhp == NULL)
1679                                 {
1680                                 al=SSL_AD_HANDSHAKE_FAILURE;
1681                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1682                                 goto f_err;
1683                                 }
1684
1685                         if (s->s3->tmp.ecdh != NULL)
1686                                 {
1687                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1688                                 goto err;
1689                                 }
1690
1691                         /* Duplicate the ECDH structure. */
1692                         if (ecdhp == NULL)
1693                                 {
1694                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1695                                 goto err;
1696                                 }
1697                         if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1698                                 {
1699                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1700                                 goto err;
1701                                 }
1702
1703                         s->s3->tmp.ecdh=ecdh;
1704                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1705                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1706                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1707                                 {
1708                                 if(!EC_KEY_generate_key(ecdh))
1709                                     {
1710                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1711                                     goto err;
1712                                     }
1713                                 }
1714
1715                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1716                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1717                             (EC_KEY_get0_private_key(ecdh) == NULL))
1718                                 {
1719                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1720                                 goto err;
1721                                 }
1722
1723                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1724                             (EC_GROUP_get_degree(group) > 163)) 
1725                                 {
1726                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1727                                 goto err;
1728                                 }
1729
1730                         /* XXX: For now, we only support ephemeral ECDH
1731                          * keys over named (not generic) curves. For 
1732                          * supported named curves, curve_id is non-zero.
1733                          */
1734                         if ((curve_id = 
1735                             tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1736                             == 0)
1737                                 {
1738                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1739                                 goto err;
1740                                 }
1741
1742                         /* Encode the public key.
1743                          * First check the size of encoding and
1744                          * allocate memory accordingly.
1745                          */
1746                         encodedlen = EC_POINT_point2oct(group, 
1747                             EC_KEY_get0_public_key(ecdh),
1748                             POINT_CONVERSION_UNCOMPRESSED, 
1749                             NULL, 0, NULL);
1750
1751                         encodedPoint = (unsigned char *) 
1752                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1753                         bn_ctx = BN_CTX_new();
1754                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1755                                 {
1756                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1757                                 goto err;
1758                                 }
1759
1760
1761                         encodedlen = EC_POINT_point2oct(group, 
1762                             EC_KEY_get0_public_key(ecdh), 
1763                             POINT_CONVERSION_UNCOMPRESSED, 
1764                             encodedPoint, encodedlen, bn_ctx);
1765
1766                         if (encodedlen == 0) 
1767                                 {
1768                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1769                                 goto err;
1770                                 }
1771
1772                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1773
1774                         /* XXX: For now, we only support named (not 
1775                          * generic) curves in ECDH ephemeral key exchanges.
1776                          * In this situation, we need four additional bytes
1777                          * to encode the entire ServerECDHParams
1778                          * structure. 
1779                          */
1780                         n = 4 + encodedlen;
1781
1782                         /* We'll generate the serverKeyExchange message
1783                          * explicitly so we can set these to NULLs
1784                          */
1785                         r[0]=NULL;
1786                         r[1]=NULL;
1787                         r[2]=NULL;
1788                         r[3]=NULL;
1789                         }
1790                 else 
1791 #endif /* !OPENSSL_NO_ECDH */
1792 #ifndef OPENSSL_NO_PSK
1793                         if (type & SSL_kPSK)
1794                                 {
1795                                 /* reserve size for record length and PSK identity hint*/
1796                                 n+=2+strlen(s->ctx->psk_identity_hint);
1797                                 }
1798                         else
1799 #endif /* !OPENSSL_NO_PSK */
1800 #ifndef OPENSSL_NO_SRP
1801                 if (type & SSL_kSRP)
1802                         {
1803                         if ((s->srp_ctx.N == NULL) ||
1804                                 (s->srp_ctx.g == NULL) ||
1805                                 (s->srp_ctx.s == NULL) ||
1806                                 (s->srp_ctx.B == NULL))
1807                                 {
1808                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1809                                 goto err;
1810                                 }
1811                         r[0]=s->srp_ctx.N;
1812                         r[1]=s->srp_ctx.g;
1813                         r[2]=s->srp_ctx.s;
1814                         r[3]=s->srp_ctx.B;
1815                         }
1816                 else 
1817 #endif
1818                         {
1819                         al=SSL_AD_HANDSHAKE_FAILURE;
1820                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1821                         goto f_err;
1822                         }
1823                 for (i=0; r[i] != NULL && i<4; i++)
1824                         {
1825                         nr[i]=BN_num_bytes(r[i]);
1826 #ifndef OPENSSL_NO_SRP
1827                         if ((i == 2) && (type & SSL_kSRP))
1828                                 n+=1+nr[i];
1829                         else
1830 #endif
1831                         n+=2+nr[i];
1832                         }
1833
1834                 if (!(s->s3->tmp.new_cipher->algorithm_auth & SSL_aNULL)
1835                         && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1836                         {
1837                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1838                                 == NULL)
1839                                 {
1840                                 al=SSL_AD_DECODE_ERROR;
1841                                 goto f_err;
1842                                 }
1843                         kn=EVP_PKEY_size(pkey);
1844                         }
1845                 else
1846                         {
1847                         pkey=NULL;
1848                         kn=0;
1849                         }
1850
1851                 if (!BUF_MEM_grow_clean(buf,n+4+kn))
1852                         {
1853                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1854                         goto err;
1855                         }
1856                 d=(unsigned char *)s->init_buf->data;
1857                 p= &(d[4]);
1858
1859                 for (i=0; r[i] != NULL && i<4; i++)
1860                         {
1861 #ifndef OPENSSL_NO_SRP
1862                         if ((i == 2) && (type & SSL_kSRP))
1863                                 {
1864                                 *p = nr[i];
1865                                 p++;
1866                                 }
1867                         else
1868 #endif
1869                         s2n(nr[i],p);
1870                         BN_bn2bin(r[i],p);
1871                         p+=nr[i];
1872                         }
1873
1874 #ifndef OPENSSL_NO_ECDH
1875                 if (type & SSL_kEECDH) 
1876                         {
1877                         /* XXX: For now, we only support named (not generic) curves.
1878                          * In this situation, the serverKeyExchange message has:
1879                          * [1 byte CurveType], [2 byte CurveName]
1880                          * [1 byte length of encoded point], followed by
1881                          * the actual encoded point itself
1882                          */
1883                         *p = NAMED_CURVE_TYPE;
1884                         p += 1;
1885                         *p = 0;
1886                         p += 1;
1887                         *p = curve_id;
1888                         p += 1;
1889                         *p = encodedlen;
1890                         p += 1;
1891                         memcpy((unsigned char*)p, 
1892                             (unsigned char *)encodedPoint, 
1893                             encodedlen);
1894                         OPENSSL_free(encodedPoint);
1895                         encodedPoint = NULL;
1896                         p += encodedlen;
1897                         }
1898 #endif
1899
1900 #ifndef OPENSSL_NO_PSK
1901                 if (type & SSL_kPSK)
1902                         {
1903                         /* copy PSK identity hint */
1904                         s2n(strlen(s->ctx->psk_identity_hint), p); 
1905                         strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
1906                         p+=strlen(s->ctx->psk_identity_hint);
1907                         }
1908 #endif
1909
1910                 /* not anonymous */
1911                 if (pkey != NULL)
1912                         {
1913                         /* n is the length of the params, they start at &(d[4])
1914                          * and p points to the space at the end. */
1915 #ifndef OPENSSL_NO_RSA
1916                         if (pkey->type == EVP_PKEY_RSA
1917                                         && TLS1_get_version(s) < TLS1_2_VERSION)
1918                                 {
1919                                 q=md_buf;
1920                                 j=0;
1921                                 for (num=2; num > 0; num--)
1922                                         {
1923                                         EVP_MD_CTX_set_flags(&md_ctx,
1924                                                 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
1925                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
1926                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
1927                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1928                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1929                                         EVP_DigestUpdate(&md_ctx,&(d[4]),n);
1930                                         EVP_DigestFinal_ex(&md_ctx,q,
1931                                                 (unsigned int *)&i);
1932                                         q+=i;
1933                                         j+=i;
1934                                         }
1935                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
1936                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
1937                                         {
1938                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
1939                                         goto err;
1940                                         }
1941                                 s2n(u,p);
1942                                 n+=u+2;
1943                                 }
1944                         else
1945 #endif
1946                         if (md)
1947                                 {
1948                                 /* For TLS1.2 and later send signature
1949                                  * algorithm */
1950                                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
1951                                         {
1952                                         if (!tls12_get_sigandhash(p, pkey, md))
1953                                                 {
1954                                                 /* Should never happen */
1955                                                 al=SSL_AD_INTERNAL_ERROR;
1956                                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
1957                                                 goto f_err;
1958                                                 }
1959                                         p+=2;
1960                                         }
1961 #ifdef SSL_DEBUG
1962                                 fprintf(stderr, "Using hash %s\n",
1963                                                         EVP_MD_name(md));
1964 #endif
1965                                 EVP_SignInit_ex(&md_ctx, md, NULL);
1966                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
1967                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
1968                                 EVP_SignUpdate(&md_ctx,&(d[4]),n);
1969                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
1970                                         (unsigned int *)&i,pkey))
1971                                         {
1972                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
1973                                         goto err;
1974                                         }
1975                                 s2n(i,p);
1976                                 n+=i+2;
1977                                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
1978                                         n+= 2;
1979                                 }
1980                         else
1981                                 {
1982                                 /* Is this error check actually needed? */
1983                                 al=SSL_AD_HANDSHAKE_FAILURE;
1984                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
1985                                 goto f_err;
1986                                 }
1987                         }
1988
1989                 *(d++)=SSL3_MT_SERVER_KEY_EXCHANGE;
1990                 l2n3(n,d);
1991
1992                 /* we should now have things packed up, so lets send
1993                  * it off */
1994                 s->init_num=n+4;
1995                 s->init_off=0;
1996                 }
1997
1998         s->state = SSL3_ST_SW_KEY_EXCH_B;
1999         EVP_MD_CTX_cleanup(&md_ctx);
2000         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2001 f_err:
2002         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2003 err:
2004 #ifndef OPENSSL_NO_ECDH
2005         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2006         BN_CTX_free(bn_ctx);
2007 #endif
2008         EVP_MD_CTX_cleanup(&md_ctx);
2009         return(-1);
2010         }
2011
2012 int ssl3_send_certificate_request(SSL *s)
2013         {
2014         unsigned char *p,*d;
2015         int i,j,nl,off,n;
2016         STACK_OF(X509_NAME) *sk=NULL;
2017         X509_NAME *name;
2018         BUF_MEM *buf;
2019
2020         if (s->state == SSL3_ST_SW_CERT_REQ_A)
2021                 {
2022                 buf=s->init_buf;
2023
2024                 d=p=(unsigned char *)&(buf->data[4]);
2025
2026                 /* get the list of acceptable cert types */
2027                 p++;
2028                 n=ssl3_get_req_cert_type(s,p);
2029                 d[0]=n;
2030                 p+=n;
2031                 n++;
2032
2033                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2034                         {
2035                         nl = tls12_get_req_sig_algs(s, p + 2);
2036                         s2n(nl, p);
2037                         p += nl + 2;
2038                         n += nl + 2;
2039                         }
2040
2041                 off=n;
2042                 p+=2;
2043                 n+=2;
2044
2045                 sk=SSL_get_client_CA_list(s);
2046                 nl=0;
2047                 if (sk != NULL)
2048                         {
2049                         for (i=0; i<sk_X509_NAME_num(sk); i++)
2050                                 {
2051                                 name=sk_X509_NAME_value(sk,i);
2052                                 j=i2d_X509_NAME(name,NULL);
2053                                 if (!BUF_MEM_grow_clean(buf,4+n+j+2))
2054                                         {
2055                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2056                                         goto err;
2057                                         }
2058                                 p=(unsigned char *)&(buf->data[4+n]);
2059                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2060                                         {
2061                                         s2n(j,p);
2062                                         i2d_X509_NAME(name,&p);
2063                                         n+=2+j;
2064                                         nl+=2+j;
2065                                         }
2066                                 else
2067                                         {
2068                                         d=p;
2069                                         i2d_X509_NAME(name,&p);
2070                                         j-=2; s2n(j,d); j+=2;
2071                                         n+=j;
2072                                         nl+=j;
2073                                         }
2074                                 }
2075                         }
2076                 /* else no CA names */
2077                 p=(unsigned char *)&(buf->data[4+off]);
2078                 s2n(nl,p);
2079
2080                 d=(unsigned char *)buf->data;
2081                 *(d++)=SSL3_MT_CERTIFICATE_REQUEST;
2082                 l2n3(n,d);
2083
2084                 /* we should now have things packed up, so lets send
2085                  * it off */
2086
2087                 s->init_num=n+4;
2088                 s->init_off=0;
2089 #ifdef NETSCAPE_HANG_BUG
2090                 p=(unsigned char *)s->init_buf->data + s->init_num;
2091
2092                 /* do the header */
2093                 *(p++)=SSL3_MT_SERVER_DONE;
2094                 *(p++)=0;
2095                 *(p++)=0;
2096                 *(p++)=0;
2097                 s->init_num += 4;
2098 #endif
2099
2100                 s->state = SSL3_ST_SW_CERT_REQ_B;
2101                 }
2102
2103         /* SSL3_ST_SW_CERT_REQ_B */
2104         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
2105 err:
2106         return(-1);
2107         }
2108
2109 int ssl3_get_client_key_exchange(SSL *s)
2110         {
2111         int i,al,ok;
2112         long n;
2113         unsigned long alg_k;
2114         unsigned char *p;
2115 #ifndef OPENSSL_NO_RSA
2116         RSA *rsa=NULL;
2117         EVP_PKEY *pkey=NULL;
2118 #endif
2119 #ifndef OPENSSL_NO_DH
2120         BIGNUM *pub=NULL;
2121         DH *dh_srvr;
2122 #endif
2123 #ifndef OPENSSL_NO_KRB5
2124         KSSL_ERR kssl_err;
2125 #endif /* OPENSSL_NO_KRB5 */
2126
2127 #ifndef OPENSSL_NO_ECDH
2128         EC_KEY *srvr_ecdh = NULL;
2129         EVP_PKEY *clnt_pub_pkey = NULL;
2130         EC_POINT *clnt_ecpoint = NULL;
2131         BN_CTX *bn_ctx = NULL; 
2132 #endif
2133
2134         n=s->method->ssl_get_message(s,
2135                 SSL3_ST_SR_KEY_EXCH_A,
2136                 SSL3_ST_SR_KEY_EXCH_B,
2137                 SSL3_MT_CLIENT_KEY_EXCHANGE,
2138                 2048, /* ??? */
2139                 &ok);
2140
2141         if (!ok) return((int)n);
2142         p=(unsigned char *)s->init_msg;
2143
2144         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2145
2146 #ifndef OPENSSL_NO_RSA
2147         if (alg_k & SSL_kRSA)
2148                 {
2149                 /* FIX THIS UP EAY EAY EAY EAY */
2150                 if (s->s3->tmp.use_rsa_tmp)
2151                         {
2152                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2153                                 rsa=s->cert->rsa_tmp;
2154                         /* Don't do a callback because rsa_tmp should
2155                          * be sent already */
2156                         if (rsa == NULL)
2157                                 {
2158                                 al=SSL_AD_HANDSHAKE_FAILURE;
2159                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2160                                 goto f_err;
2161
2162                                 }
2163                         }
2164                 else
2165                         {
2166                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2167                         if (    (pkey == NULL) ||
2168                                 (pkey->type != EVP_PKEY_RSA) ||
2169                                 (pkey->pkey.rsa == NULL))
2170                                 {
2171                                 al=SSL_AD_HANDSHAKE_FAILURE;
2172                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2173                                 goto f_err;
2174                                 }
2175                         rsa=pkey->pkey.rsa;
2176                         }
2177
2178                 /* TLS and [incidentally] DTLS{0xFEFF} */
2179                 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2180                         {
2181                         n2s(p,i);
2182                         if (n != i+2)
2183                                 {
2184                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
2185                                         {
2186                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2187                                         goto err;
2188                                         }
2189                                 else
2190                                         p-=2;
2191                                 }
2192                         else
2193                                 n=i;
2194                         }
2195
2196                 i=RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2197
2198                 al = -1;
2199                 
2200                 if (i != SSL_MAX_MASTER_KEY_LENGTH)
2201                         {
2202                         al=SSL_AD_DECODE_ERROR;
2203                         /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_RSA_DECRYPT); */
2204                         }
2205
2206                 if ((al == -1) && !((p[0] == (s->client_version>>8)) && (p[1] == (s->client_version & 0xff))))
2207                         {
2208                         /* The premaster secret must contain the same version number as the
2209                          * ClientHello to detect version rollback attacks (strangely, the
2210                          * protocol does not offer such protection for DH ciphersuites).
2211                          * However, buggy clients exist that send the negotiated protocol
2212                          * version instead if the server does not support the requested
2213                          * protocol version.
2214                          * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2215                         if (!((s->options & SSL_OP_TLS_ROLLBACK_BUG) &&
2216                                 (p[0] == (s->version>>8)) && (p[1] == (s->version & 0xff))))
2217                                 {
2218                                 al=SSL_AD_DECODE_ERROR;
2219                                 /* SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_PROTOCOL_VERSION_NUMBER); */
2220
2221                                 /* The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2222                                  * (http://eprint.iacr.org/2003/052/) exploits the version
2223                                  * number check as a "bad version oracle" -- an alert would
2224                                  * reveal that the plaintext corresponding to some ciphertext
2225                                  * made up by the adversary is properly formatted except
2226                                  * that the version number is wrong.  To avoid such attacks,
2227                                  * we should treat this just like any other decryption error. */
2228                                 }
2229                         }
2230
2231                 if (al != -1)
2232                         {
2233                         /* Some decryption failure -- use random value instead as countermeasure
2234                          * against Bleichenbacher's attack on PKCS #1 v1.5 RSA padding
2235                          * (see RFC 2246, section 7.4.7.1). */
2236                         ERR_clear_error();
2237                         i = SSL_MAX_MASTER_KEY_LENGTH;
2238                         p[0] = s->client_version >> 8;
2239                         p[1] = s->client_version & 0xff;
2240                         if (RAND_pseudo_bytes(p+2, i-2) <= 0) /* should be RAND_bytes, but we cannot work around a failure */
2241                                 goto err;
2242                         }
2243         
2244                 s->session->master_key_length=
2245                         s->method->ssl3_enc->generate_master_secret(s,
2246                                 s->session->master_key,
2247                                 p,i);
2248                 OPENSSL_cleanse(p,i);
2249                 }
2250         else
2251 #endif
2252 #ifndef OPENSSL_NO_DH
2253                 if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2254                 {
2255                 n2s(p,i);
2256                 if (n != i+2)
2257                         {
2258                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2259                                 {
2260                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2261                                 goto err;
2262                                 }
2263                         else
2264                                 {
2265                                 p-=2;
2266                                 i=(int)n;
2267                                 }
2268                         }
2269
2270                 if (n == 0L) /* the parameters are in the cert */
2271                         {
2272                         al=SSL_AD_HANDSHAKE_FAILURE;
2273                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_UNABLE_TO_DECODE_DH_CERTS);
2274                         goto f_err;
2275                         }
2276                 else
2277                         {
2278                         if (s->s3->tmp.dh == NULL)
2279                                 {
2280                                 al=SSL_AD_HANDSHAKE_FAILURE;
2281                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2282                                 goto f_err;
2283                                 }
2284                         else
2285                                 dh_srvr=s->s3->tmp.dh;
2286                         }
2287
2288                 pub=BN_bin2bn(p,i,NULL);
2289                 if (pub == NULL)
2290                         {
2291                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2292                         goto err;
2293                         }
2294
2295                 i=DH_compute_key(p,pub,dh_srvr);
2296
2297                 if (i <= 0)
2298                         {
2299                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2300                         goto err;
2301                         }
2302
2303                 DH_free(s->s3->tmp.dh);
2304                 s->s3->tmp.dh=NULL;
2305
2306                 BN_clear_free(pub);
2307                 pub=NULL;
2308                 s->session->master_key_length=
2309                         s->method->ssl3_enc->generate_master_secret(s,
2310                                 s->session->master_key,p,i);
2311                 OPENSSL_cleanse(p,i);
2312                 }
2313         else
2314 #endif
2315 #ifndef OPENSSL_NO_KRB5
2316         if (alg_k & SSL_kKRB5)
2317                 {
2318                 krb5_error_code         krb5rc;
2319                 krb5_data               enc_ticket;
2320                 krb5_data               authenticator;
2321                 krb5_data               enc_pms;
2322                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
2323                 EVP_CIPHER_CTX          ciph_ctx;
2324                 const EVP_CIPHER        *enc = NULL;
2325                 unsigned char           iv[EVP_MAX_IV_LENGTH];
2326                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
2327                                                + EVP_MAX_BLOCK_LENGTH];
2328                 int                  padl, outl;
2329                 krb5_timestamp          authtime = 0;
2330                 krb5_ticket_times       ttimes;
2331
2332                 EVP_CIPHER_CTX_init(&ciph_ctx);
2333
2334                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
2335
2336                 n2s(p,i);
2337                 enc_ticket.length = i;
2338
2339                 if (n < (long)(enc_ticket.length + 6))
2340                         {
2341                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2342                                 SSL_R_DATA_LENGTH_TOO_LONG);
2343                         goto err;
2344                         }
2345
2346                 enc_ticket.data = (char *)p;
2347                 p+=enc_ticket.length;
2348
2349                 n2s(p,i);
2350                 authenticator.length = i;
2351
2352                 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2353                         {
2354                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2355                                 SSL_R_DATA_LENGTH_TOO_LONG);
2356                         goto err;
2357                         }
2358
2359                 authenticator.data = (char *)p;
2360                 p+=authenticator.length;
2361
2362                 n2s(p,i);
2363                 enc_pms.length = i;
2364                 enc_pms.data = (char *)p;
2365                 p+=enc_pms.length;
2366
2367                 /* Note that the length is checked again below,
2368                 ** after decryption
2369                 */
2370                 if(enc_pms.length > sizeof pms)
2371                         {
2372                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2373                                SSL_R_DATA_LENGTH_TOO_LONG);
2374                         goto err;
2375                         }
2376
2377                 if (n != (long)(enc_ticket.length + authenticator.length +
2378                                                 enc_pms.length + 6))
2379                         {
2380                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2381                                 SSL_R_DATA_LENGTH_TOO_LONG);
2382                         goto err;
2383                         }
2384
2385                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2386                                         &kssl_err)) != 0)
2387                         {
2388 #ifdef KSSL_DEBUG
2389                         printf("kssl_sget_tkt rtn %d [%d]\n",
2390                                 krb5rc, kssl_err.reason);
2391                         if (kssl_err.text)
2392                                 printf("kssl_err text= %s\n", kssl_err.text);
2393 #endif  /* KSSL_DEBUG */
2394                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2395                                 kssl_err.reason);
2396                         goto err;
2397                         }
2398
2399                 /*  Note: no authenticator is not considered an error,
2400                 **  but will return authtime == 0.
2401                 */
2402                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2403                                         &authtime, &kssl_err)) != 0)
2404                         {
2405 #ifdef KSSL_DEBUG
2406                         printf("kssl_check_authent rtn %d [%d]\n",
2407                                 krb5rc, kssl_err.reason);
2408                         if (kssl_err.text)
2409                                 printf("kssl_err text= %s\n", kssl_err.text);
2410 #endif  /* KSSL_DEBUG */
2411                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2412                                 kssl_err.reason);
2413                         goto err;
2414                         }
2415
2416                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2417                         {
2418                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2419                         goto err;
2420                         }
2421
2422 #ifdef KSSL_DEBUG
2423                 kssl_ctx_show(kssl_ctx);
2424 #endif  /* KSSL_DEBUG */
2425
2426                 enc = kssl_map_enc(kssl_ctx->enctype);
2427                 if (enc == NULL)
2428                     goto err;
2429
2430                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
2431
2432                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2433                         {
2434                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2435                                 SSL_R_DECRYPTION_FAILED);
2436                         goto err;
2437                         }
2438                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2439                                         (unsigned char *)enc_pms.data, enc_pms.length))
2440                         {
2441                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2442                                 SSL_R_DECRYPTION_FAILED);
2443                         goto err;
2444                         }
2445                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2446                         {
2447                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2448                                 SSL_R_DATA_LENGTH_TOO_LONG);
2449                         goto err;
2450                         }
2451                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2452                         {
2453                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2454                                 SSL_R_DECRYPTION_FAILED);
2455                         goto err;
2456                         }
2457                 outl += padl;
2458                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2459                         {
2460                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2461                                 SSL_R_DATA_LENGTH_TOO_LONG);
2462                         goto err;
2463                         }
2464                 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2465                     {
2466                     /* The premaster secret must contain the same version number as the
2467                      * ClientHello to detect version rollback attacks (strangely, the
2468                      * protocol does not offer such protection for DH ciphersuites).
2469                      * However, buggy clients exist that send random bytes instead of
2470                      * the protocol version.
2471                      * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. 
2472                      * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2473                      */
2474                     if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2475                         {
2476                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2477                                SSL_AD_DECODE_ERROR);
2478                         goto err;
2479                         }
2480                     }
2481
2482                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2483
2484                 s->session->master_key_length=
2485                         s->method->ssl3_enc->generate_master_secret(s,
2486                                 s->session->master_key, pms, outl);
2487
2488                 if (kssl_ctx->client_princ)
2489                         {
2490                         size_t len = strlen(kssl_ctx->client_princ);
2491                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
2492                                 {
2493                                 s->session->krb5_client_princ_len = len;
2494                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2495                                 }
2496                         }
2497
2498
2499                 /*  Was doing kssl_ctx_free() here,
2500                 **  but it caused problems for apache.
2501                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
2502                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2503                 */
2504                 }
2505         else
2506 #endif  /* OPENSSL_NO_KRB5 */
2507
2508 #ifndef OPENSSL_NO_ECDH
2509                 if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2510                 {
2511                 int ret = 1;
2512                 int field_size = 0;
2513                 const EC_KEY   *tkey;
2514                 const EC_GROUP *group;
2515                 const BIGNUM *priv_key;
2516
2517                 /* initialize structures for server's ECDH key pair */
2518                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2519                         {
2520                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2521                             ERR_R_MALLOC_FAILURE);
2522                         goto err;
2523                         }
2524
2525                 /* Let's get server private key and group information */
2526                 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2527                         { 
2528                         /* use the certificate */
2529                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2530                         }
2531                 else
2532                         {
2533                         /* use the ephermeral values we saved when
2534                          * generating the ServerKeyExchange msg.
2535                          */
2536                         tkey = s->s3->tmp.ecdh;
2537                         }
2538
2539                 group    = EC_KEY_get0_group(tkey);
2540                 priv_key = EC_KEY_get0_private_key(tkey);
2541
2542                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2543                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2544                         {
2545                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2546                                ERR_R_EC_LIB);
2547                         goto err;
2548                         }
2549
2550                 /* Let's get client's public key */
2551                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2552                         {
2553                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2554                             ERR_R_MALLOC_FAILURE);
2555                         goto err;
2556                         }
2557
2558                 if (n == 0L) 
2559                         {
2560                         /* Client Publickey was in Client Certificate */
2561
2562                          if (alg_k & SSL_kEECDH)
2563                                  {
2564                                  al=SSL_AD_HANDSHAKE_FAILURE;
2565                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2566                                  goto f_err;
2567                                  }
2568                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2569                             == NULL) || 
2570                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2571                                 {
2572                                 /* XXX: For now, we do not support client
2573                                  * authentication using ECDH certificates
2574                                  * so this branch (n == 0L) of the code is
2575                                  * never executed. When that support is
2576                                  * added, we ought to ensure the key 
2577                                  * received in the certificate is 
2578                                  * authorized for key agreement.
2579                                  * ECDH_compute_key implicitly checks that
2580                                  * the two ECDH shares are for the same
2581                                  * group.
2582                                  */
2583                                 al=SSL_AD_HANDSHAKE_FAILURE;
2584                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2585                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2586                                 goto f_err;
2587                                 }
2588
2589                         if (EC_POINT_copy(clnt_ecpoint,
2590                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2591                                 {
2592                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2593                                         ERR_R_EC_LIB);
2594                                 goto err;
2595                                 }
2596                         ret = 2; /* Skip certificate verify processing */
2597                         }
2598                 else
2599                         {
2600                         /* Get client's public key from encoded point
2601                          * in the ClientKeyExchange message.
2602                          */
2603                         if ((bn_ctx = BN_CTX_new()) == NULL)
2604                                 {
2605                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2606                                     ERR_R_MALLOC_FAILURE);
2607                                 goto err;
2608                                 }
2609
2610                         /* Get encoded point length */
2611                         i = *p; 
2612                         p += 1;
2613                         if (n != 1 + i)
2614                                 {
2615                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2616                                     ERR_R_EC_LIB);
2617                                 goto err;
2618                                 }
2619                         if (EC_POINT_oct2point(group, 
2620                             clnt_ecpoint, p, i, bn_ctx) == 0)
2621                                 {
2622                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2623                                     ERR_R_EC_LIB);
2624                                 goto err;
2625                                 }
2626                         /* p is pointing to somewhere in the buffer
2627                          * currently, so set it to the start 
2628                          */ 
2629                         p=(unsigned char *)s->init_buf->data;
2630                         }
2631
2632                 /* Compute the shared pre-master secret */
2633                 field_size = EC_GROUP_get_degree(group);
2634                 if (field_size <= 0)
2635                         {
2636                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, 
2637                                ERR_R_ECDH_LIB);
2638                         goto err;
2639                         }
2640                 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2641                 if (i <= 0)
2642                         {
2643                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2644                             ERR_R_ECDH_LIB);
2645                         goto err;
2646                         }
2647
2648                 EVP_PKEY_free(clnt_pub_pkey);
2649                 EC_POINT_free(clnt_ecpoint);
2650                 EC_KEY_free(srvr_ecdh);
2651                 BN_CTX_free(bn_ctx);
2652                 EC_KEY_free(s->s3->tmp.ecdh);
2653                 s->s3->tmp.ecdh = NULL; 
2654
2655                 /* Compute the master secret */
2656                 s->session->master_key_length = s->method->ssl3_enc-> \
2657                     generate_master_secret(s, s->session->master_key, p, i);
2658                 
2659                 OPENSSL_cleanse(p, i);
2660                 return (ret);
2661                 }
2662         else
2663 #endif
2664 #ifndef OPENSSL_NO_PSK
2665                 if (alg_k & SSL_kPSK)
2666                         {
2667                         unsigned char *t = NULL;
2668                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2669                         unsigned int pre_ms_len = 0, psk_len = 0;
2670                         int psk_err = 1;
2671                         char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2672
2673                         al=SSL_AD_HANDSHAKE_FAILURE;
2674
2675                         n2s(p,i);
2676                         if (n != i+2)
2677                                 {
2678                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2679                                         SSL_R_LENGTH_MISMATCH);
2680                                 goto psk_err;
2681                                 }
2682                         if (i > PSK_MAX_IDENTITY_LEN)
2683                                 {
2684                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2685                                         SSL_R_DATA_LENGTH_TOO_LONG);
2686                                 goto psk_err;
2687                                 }
2688                         if (s->psk_server_callback == NULL)
2689                                 {
2690                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2691                                        SSL_R_PSK_NO_SERVER_CB);
2692                                 goto psk_err;
2693                                 }
2694
2695                         /* Create guaranteed NULL-terminated identity
2696                          * string for the callback */
2697                         memcpy(tmp_id, p, i);
2698                         memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2699                         psk_len = s->psk_server_callback(s, tmp_id,
2700                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2701                         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2702
2703                         if (psk_len > PSK_MAX_PSK_LEN)
2704                                 {
2705                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2706                                         ERR_R_INTERNAL_ERROR);
2707                                 goto psk_err;
2708                                 }
2709                         else if (psk_len == 0)
2710                                 {
2711                                 /* PSK related to the given identity not found */
2712                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2713                                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2714                                 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2715                                 goto psk_err;
2716                                 }
2717
2718                         /* create PSK pre_master_secret */
2719                         pre_ms_len=2+psk_len+2+psk_len;
2720                         t = psk_or_pre_ms;
2721                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2722                         s2n(psk_len, t);
2723                         memset(t, 0, psk_len);
2724                         t+=psk_len;
2725                         s2n(psk_len, t);
2726
2727                         if (s->session->psk_identity != NULL)
2728                                 OPENSSL_free(s->session->psk_identity);
2729                         s->session->psk_identity = BUF_strdup((char *)p);
2730                         if (s->session->psk_identity == NULL)
2731                                 {
2732                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2733                                         ERR_R_MALLOC_FAILURE);
2734                                 goto psk_err;
2735                                 }
2736
2737                         if (s->session->psk_identity_hint != NULL)
2738                                 OPENSSL_free(s->session->psk_identity_hint);
2739                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2740                         if (s->ctx->psk_identity_hint != NULL &&
2741                                 s->session->psk_identity_hint == NULL)
2742                                 {
2743                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2744                                         ERR_R_MALLOC_FAILURE);
2745                                 goto psk_err;
2746                                 }
2747
2748                         s->session->master_key_length=
2749                                 s->method->ssl3_enc->generate_master_secret(s,
2750                                         s->session->master_key, psk_or_pre_ms, pre_ms_len);
2751                         psk_err = 0;
2752                 psk_err:
2753                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2754                         if (psk_err != 0)
2755                                 goto f_err;
2756                         }
2757                 else
2758 #endif
2759 #ifndef OPENSSL_NO_SRP
2760                 if (alg_k & SSL_kSRP)
2761                         {
2762                         int param_len;
2763
2764                         n2s(p,i);
2765                         param_len=i+2;
2766                         if (param_len > n)
2767                                 {
2768                                 al=SSL_AD_DECODE_ERROR;
2769                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2770                                 goto f_err;
2771                                 }
2772                         if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2773                                 {
2774                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2775                                 goto err;
2776                                 }
2777                         if (s->session->srp_username != NULL)
2778                                 OPENSSL_free(s->session->srp_username);
2779                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2780                         if (s->session->srp_username == NULL)
2781                                 {
2782                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2783                                         ERR_R_MALLOC_FAILURE);
2784                                 goto err;
2785                                 }
2786
2787                         if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2788                                 {
2789                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2790                                 goto err;
2791                                 }
2792
2793                         p+=i;
2794                         }
2795                 else
2796 #endif  /* OPENSSL_NO_SRP */
2797                 if (alg_k & SSL_kGOST) 
2798                         {
2799                         int ret = 0;
2800                         EVP_PKEY_CTX *pkey_ctx;
2801                         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2802                         unsigned char premaster_secret[32], *start;
2803                         size_t outlen=32, inlen;
2804                         unsigned long alg_a;
2805
2806                         /* Get our certificate private key*/
2807                         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2808                         if (alg_a & SSL_aGOST94)
2809                                 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2810                         else if (alg_a & SSL_aGOST01)
2811                                 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2812
2813                         pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2814                         EVP_PKEY_decrypt_init(pkey_ctx);
2815                         /* If client certificate is present and is of the same type, maybe
2816                          * use it for key exchange.  Don't mind errors from
2817                          * EVP_PKEY_derive_set_peer, because it is completely valid to use
2818                          * a client certificate for authorization only. */
2819                         client_pub_pkey = X509_get_pubkey(s->session->peer);
2820                         if (client_pub_pkey)
2821                                 {
2822                                 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2823                                         ERR_clear_error();
2824                                 }
2825                         /* Decrypt session key */
2826                         if ((*p!=( V_ASN1_SEQUENCE| V_ASN1_CONSTRUCTED))) 
2827                                 {
2828                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2829                                 goto gerr;
2830                                 }
2831                         if (p[1] == 0x81)
2832                                 {
2833                                 start = p+3;
2834                                 inlen = p[2];
2835                                 }
2836                         else if (p[1] < 0x80)
2837                                 {
2838                                 start = p+2;
2839                                 inlen = p[1];
2840                                 }
2841                         else
2842                                 {
2843                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2844                                 goto gerr;
2845                                 }
2846                         if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) 
2847
2848                                 {
2849                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2850                                 goto gerr;
2851                                 }
2852                         /* Generate master secret */
2853                         s->session->master_key_length=
2854                                 s->method->ssl3_enc->generate_master_secret(s,
2855                                         s->session->master_key,premaster_secret,32);
2856                         /* Check if pubkey from client certificate was used */
2857                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2858                                 ret = 2;
2859                         else
2860                                 ret = 1;
2861                 gerr:
2862                         EVP_PKEY_free(client_pub_pkey);
2863                         EVP_PKEY_CTX_free(pkey_ctx);
2864                         if (ret)
2865                                 return ret;
2866                         else
2867                                 goto err;
2868                         }
2869                 else
2870                 {
2871                 al=SSL_AD_HANDSHAKE_FAILURE;
2872                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2873                                 SSL_R_UNKNOWN_CIPHER_TYPE);
2874                 goto f_err;
2875                 }
2876
2877         return(1);
2878 f_err:
2879         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2880 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
2881 err:
2882 #endif
2883 #ifndef OPENSSL_NO_ECDH
2884         EVP_PKEY_free(clnt_pub_pkey);
2885         EC_POINT_free(clnt_ecpoint);
2886         if (srvr_ecdh != NULL) 
2887                 EC_KEY_free(srvr_ecdh);
2888         BN_CTX_free(bn_ctx);
2889 #endif
2890         return(-1);
2891         }
2892
2893 int ssl3_get_cert_verify(SSL *s)
2894         {
2895         EVP_PKEY *pkey=NULL;
2896         unsigned char *p;
2897         int al,ok,ret=0;
2898         long n;
2899         int type=0,i,j;
2900         X509 *peer;
2901         const EVP_MD *md = NULL;
2902         EVP_MD_CTX mctx;
2903         EVP_MD_CTX_init(&mctx);
2904
2905         n=s->method->ssl_get_message(s,
2906                 SSL3_ST_SR_CERT_VRFY_A,
2907                 SSL3_ST_SR_CERT_VRFY_B,
2908                 -1,
2909                 514, /* 514? */
2910                 &ok);
2911
2912         if (!ok) return((int)n);
2913
2914         if (s->session->peer != NULL)
2915                 {
2916                 peer=s->session->peer;
2917                 pkey=X509_get_pubkey(peer);
2918                 type=X509_certificate_type(peer,pkey);
2919                 }
2920         else
2921                 {
2922                 peer=NULL;
2923                 pkey=NULL;
2924                 }
2925
2926         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
2927                 {
2928                 s->s3->tmp.reuse_message=1;
2929                 if ((peer != NULL) && (type | EVP_PKT_SIGN))
2930                         {
2931                         al=SSL_AD_UNEXPECTED_MESSAGE;
2932                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
2933                         goto f_err;
2934                         }
2935                 ret=1;
2936                 goto end;
2937                 }
2938
2939         if (peer == NULL)
2940                 {
2941                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
2942                 al=SSL_AD_UNEXPECTED_MESSAGE;
2943                 goto f_err;
2944                 }
2945
2946         if (!(type & EVP_PKT_SIGN))
2947                 {
2948                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
2949                 al=SSL_AD_ILLEGAL_PARAMETER;
2950                 goto f_err;
2951                 }
2952
2953         if (s->s3->change_cipher_spec)
2954                 {
2955                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
2956                 al=SSL_AD_UNEXPECTED_MESSAGE;
2957                 goto f_err;
2958                 }
2959
2960         /* we now have a signature that we need to verify */
2961         p=(unsigned char *)s->init_msg;
2962         /* Check for broken implementations of GOST ciphersuites */
2963         /* If key is GOST and n is exactly 64, it is bare
2964          * signature without length field */
2965         if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
2966                 pkey->type == NID_id_GostR3410_2001) )
2967                 {
2968                 i=64;
2969                 } 
2970         else 
2971                 {       
2972                 if (TLS1_get_version(s) >= TLS1_2_VERSION)
2973                         {
2974                         int sigalg = tls12_get_sigid(pkey);
2975                         /* Should never happen */
2976                         if (sigalg == -1)
2977                                 {
2978                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
2979                                 al=SSL_AD_INTERNAL_ERROR;
2980                                 goto f_err;
2981                                 }
2982                         /* Check key type is consistent with signature */
2983                         if (sigalg != (int)p[1])
2984                                 {
2985                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_TYPE);
2986                                 al=SSL_AD_DECODE_ERROR;
2987                                 goto f_err;
2988                                 }
2989                         md = tls12_get_hash(p[0]);
2990                         if (md == NULL)
2991                                 {
2992                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_UNKNOWN_DIGEST);
2993                                 al=SSL_AD_DECODE_ERROR;
2994                                 goto f_err;
2995                                 }
2996 #ifdef SSL_DEBUG
2997 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
2998 #endif
2999                         p += 2;
3000                         n -= 2;
3001                         }
3002                 n2s(p,i);
3003                 n-=2;
3004                 if (i > n)
3005                         {
3006                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3007                         al=SSL_AD_DECODE_ERROR;
3008                         goto f_err;
3009                         }
3010         }
3011         j=EVP_PKEY_size(pkey);
3012         if ((i > j) || (n > j) || (n <= 0))
3013                 {
3014                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3015                 al=SSL_AD_DECODE_ERROR;
3016                 goto f_err;
3017                 }
3018
3019         if (TLS1_get_version(s) >= TLS1_2_VERSION)
3020                 {
3021                 long hdatalen = 0;
3022                 void *hdata;
3023                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3024                 if (hdatalen <= 0)
3025                         {
3026                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3027                         al=SSL_AD_INTERNAL_ERROR;
3028                         goto f_err;
3029                         }
3030 #ifdef SSL_DEBUG
3031                 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3032                                                         EVP_MD_name(md));
3033 #endif
3034                 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3035                         || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3036                         {
3037                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3038                         al=SSL_AD_INTERNAL_ERROR;
3039                         goto f_err;
3040                         }
3041
3042                 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3043                         {
3044                         al=SSL_AD_DECRYPT_ERROR;
3045                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3046                         goto f_err;
3047                         }
3048                 }
3049         else
3050 #ifndef OPENSSL_NO_RSA 
3051         if (pkey->type == EVP_PKEY_RSA)
3052                 {
3053                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3054                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
3055                                                         pkey->pkey.rsa);
3056                 if (i < 0)
3057                         {
3058                         al=SSL_AD_DECRYPT_ERROR;
3059                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3060                         goto f_err;
3061                         }
3062                 if (i == 0)
3063                         {
3064                         al=SSL_AD_DECRYPT_ERROR;
3065                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3066                         goto f_err;
3067                         }
3068                 }
3069         else
3070 #endif
3071 #ifndef OPENSSL_NO_DSA
3072                 if (pkey->type == EVP_PKEY_DSA)
3073                 {
3074                 j=DSA_verify(pkey->save_type,
3075                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3076                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3077                 if (j <= 0)
3078                         {
3079                         /* bad signature */
3080                         al=SSL_AD_DECRYPT_ERROR;
3081                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3082                         goto f_err;
3083                         }
3084                 }
3085         else
3086 #endif
3087 #ifndef OPENSSL_NO_ECDSA
3088                 if (pkey->type == EVP_PKEY_EC)
3089                 {
3090                 j=ECDSA_verify(pkey->save_type,
3091                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3092                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3093                 if (j <= 0)
3094                         {
3095                         /* bad signature */
3096                         al=SSL_AD_DECRYPT_ERROR;
3097                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3098                             SSL_R_BAD_ECDSA_SIGNATURE);
3099                         goto f_err;
3100                         }
3101                 }
3102         else
3103 #endif
3104         if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3105                 {   unsigned char signature[64];
3106                         int idx;
3107                         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3108                         EVP_PKEY_verify_init(pctx);
3109                         if (i!=64) {
3110                                 fprintf(stderr,"GOST signature length is %d",i);
3111                         }       
3112                         for (idx=0;idx<64;idx++) {
3113                                 signature[63-idx]=p[idx];
3114                         }       
3115                         j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3116                         EVP_PKEY_CTX_free(pctx);
3117                         if (j<=0) 
3118                                 {
3119                                 al=SSL_AD_DECRYPT_ERROR;
3120                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3121                                         SSL_R_BAD_ECDSA_SIGNATURE);
3122                                 goto f_err;
3123                                 }       
3124                 }
3125         else    
3126                 {
3127                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3128                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3129                 goto f_err;
3130                 }
3131
3132
3133         ret=1;
3134         if (0)
3135                 {
3136 f_err:
3137                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3138                 }
3139 end:
3140         if (s->s3->handshake_buffer)
3141                 {
3142                 BIO_free(s->s3->handshake_buffer);
3143                 s->s3->handshake_buffer = NULL;
3144                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3145                 }
3146         EVP_MD_CTX_cleanup(&mctx);
3147         EVP_PKEY_free(pkey);
3148         return(ret);
3149         }
3150
3151 int ssl3_get_client_certificate(SSL *s)
3152         {
3153         int i,ok,al,ret= -1;
3154         X509 *x=NULL;
3155         unsigned long l,nc,llen,n;
3156         const unsigned char *p,*q;
3157         unsigned char *d;
3158         STACK_OF(X509) *sk=NULL;
3159
3160         n=s->method->ssl_get_message(s,
3161                 SSL3_ST_SR_CERT_A,
3162                 SSL3_ST_SR_CERT_B,
3163                 -1,
3164                 s->max_cert_list,
3165                 &ok);
3166
3167         if (!ok) return((int)n);
3168
3169         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3170                 {
3171                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
3172                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3173                         {
3174                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3175                         al=SSL_AD_HANDSHAKE_FAILURE;
3176                         goto f_err;
3177                         }
3178                 /* If tls asked for a client cert, the client must return a 0 list */
3179                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3180                         {
3181                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3182                         al=SSL_AD_UNEXPECTED_MESSAGE;
3183                         goto f_err;
3184                         }
3185                 s->s3->tmp.reuse_message=1;
3186                 return(1);
3187                 }
3188
3189         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3190                 {
3191                 al=SSL_AD_UNEXPECTED_MESSAGE;
3192                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3193                 goto f_err;
3194                 }
3195         p=d=(unsigned char *)s->init_msg;
3196
3197         if ((sk=sk_X509_new_null()) == NULL)
3198                 {
3199                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3200                 goto err;
3201                 }
3202
3203         n2l3(p,llen);
3204         if (llen+3 != n)
3205                 {
3206                 al=SSL_AD_DECODE_ERROR;
3207                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3208                 goto f_err;
3209                 }
3210         for (nc=0; nc<llen; )
3211                 {
3212                 n2l3(p,l);
3213                 if ((l+nc+3) > llen)
3214                         {
3215                         al=SSL_AD_DECODE_ERROR;
3216                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3217                         goto f_err;
3218                         }
3219
3220                 q=p;
3221                 x=d2i_X509(NULL,&p,l);
3222                 if (x == NULL)
3223                         {
3224                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3225                         goto err;
3226                         }
3227                 if (p != (q+l))
3228                         {
3229                         al=SSL_AD_DECODE_ERROR;
3230                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3231                         goto f_err;
3232                         }
3233                 if (!sk_X509_push(sk,x))
3234                         {
3235                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3236                         goto err;
3237                         }
3238                 x=NULL;
3239                 nc+=l+3;
3240                 }
3241
3242         if (sk_X509_num(sk) <= 0)
3243                 {
3244                 /* TLS does not mind 0 certs returned */
3245                 if (s->version == SSL3_VERSION)
3246                         {
3247                         al=SSL_AD_HANDSHAKE_FAILURE;
3248                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3249                         goto f_err;
3250                         }
3251                 /* Fail for TLS only if we required a certificate */
3252                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3253                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3254                         {
3255                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3256                         al=SSL_AD_HANDSHAKE_FAILURE;
3257                         goto f_err;
3258                         }
3259                 /* No client certificate so digest cached records */
3260                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3261                         {
3262                         al=SSL_AD_INTERNAL_ERROR;
3263                         goto f_err;
3264                         }
3265                 }
3266         else
3267                 {
3268                 i=ssl_verify_cert_chain(s,sk);
3269                 if (i <= 0)
3270                         {
3271                         al=ssl_verify_alarm_type(s->verify_result);
3272                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATE_RETURNED);
3273                         goto f_err;
3274                         }
3275                 }
3276
3277         if (s->session->peer != NULL) /* This should not be needed */
3278                 X509_free(s->session->peer);
3279         s->session->peer=sk_X509_shift(sk);
3280         s->session->verify_result = s->verify_result;
3281
3282         /* With the current implementation, sess_cert will always be NULL
3283          * when we arrive here. */
3284         if (s->session->sess_cert == NULL)
3285                 {
3286                 s->session->sess_cert = ssl_sess_cert_new();
3287                 if (s->session->sess_cert == NULL)
3288                         {
3289                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3290                         goto err;
3291                         }
3292                 }
3293         if (s->session->sess_cert->cert_chain != NULL)
3294                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3295         s->session->sess_cert->cert_chain=sk;
3296         /* Inconsistency alert: cert_chain does *not* include the
3297          * peer's own certificate, while we do include it in s3_clnt.c */
3298
3299         sk=NULL;
3300
3301         ret=1;
3302         if (0)
3303                 {
3304 f_err:
3305                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3306                 }
3307 err:
3308         if (x != NULL) X509_free(x);
3309         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3310         return(ret);
3311         }
3312
3313 int ssl3_send_server_certificate(SSL *s)
3314         {
3315         unsigned long l;
3316         X509 *x;
3317
3318         if (s->state == SSL3_ST_SW_CERT_A)
3319                 {
3320                 x=ssl_get_server_send_cert(s);
3321                 if (x == NULL)
3322                         {
3323                         /* VRS: allow null cert if auth == KRB5 */
3324                         if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3325                             (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3326                                 {
3327                                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3328                                 return(0);
3329                                 }
3330                         }
3331
3332                 l=ssl3_output_cert_chain(s,x);
3333                 s->state=SSL3_ST_SW_CERT_B;
3334                 s->init_num=(int)l;
3335                 s->init_off=0;
3336                 }
3337
3338         /* SSL3_ST_SW_CERT_B */
3339         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3340         }
3341
3342 #ifndef OPENSSL_NO_TLSEXT
3343 /* send a new session ticket (not necessarily for a new session) */
3344 int ssl3_send_newsession_ticket(SSL *s)
3345         {
3346         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3347                 {
3348                 unsigned char *p, *senc, *macstart;
3349                 const unsigned char *const_p;
3350                 int len, slen_full, slen;
3351                 SSL_SESSION *sess;
3352                 unsigned int hlen;
3353                 EVP_CIPHER_CTX ctx;
3354                 HMAC_CTX hctx;
3355                 SSL_CTX *tctx = s->initial_ctx;
3356                 unsigned char iv[EVP_MAX_IV_LENGTH];
3357                 unsigned char key_name[16];
3358
3359                 /* get session encoding length */
3360                 slen_full = i2d_SSL_SESSION(s->session, NULL);
3361                 /* Some length values are 16 bits, so forget it if session is
3362                  * too long
3363                  */
3364                 if (slen_full > 0xFF00)
3365                         return -1;
3366                 senc = OPENSSL_malloc(slen_full);
3367                 if (!senc)
3368                         return -1;
3369                 p = senc;
3370                 i2d_SSL_SESSION(s->session, &p);
3371
3372                 /* create a fresh copy (not shared with other threads) to clean up */
3373                 const_p = senc;
3374                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3375                 if (sess == NULL)
3376                         {
3377                         OPENSSL_free(senc);
3378                         return -1;
3379                         }
3380                 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3381
3382                 slen = i2d_SSL_SESSION(sess, NULL);
3383                 if (slen > slen_full) /* shouldn't ever happen */
3384                         {
3385                         OPENSSL_free(senc);
3386                         return -1;
3387                         }
3388                 p = senc;
3389                 i2d_SSL_SESSION(sess, &p);
3390                 SSL_SESSION_free(sess);
3391
3392                 /* Grow buffer if need be: the length calculation is as
3393                  * follows 1 (size of message name) + 3 (message length
3394                  * bytes) + 4 (ticket lifetime hint) + 2 (ticket length) +
3395                  * 16 (key name) + max_iv_len (iv length) +
3396                  * session_length + max_enc_block_size (max encrypted session
3397                  * length) + max_md_size (HMAC).
3398                  */
3399                 if (!BUF_MEM_grow(s->init_buf,
3400                         26 + EVP_MAX_IV_LENGTH + EVP_MAX_BLOCK_LENGTH +
3401                         EVP_MAX_MD_SIZE + slen))
3402                         return -1;
3403
3404                 p=(unsigned char *)s->init_buf->data;
3405                 /* do the header */
3406                 *(p++)=SSL3_MT_NEWSESSION_TICKET;
3407                 /* Skip message length for now */
3408                 p += 3;
3409                 EVP_CIPHER_CTX_init(&ctx);
3410                 HMAC_CTX_init(&hctx);
3411                 /* Initialize HMAC and cipher contexts. If callback present
3412                  * it does all the work otherwise use generated values
3413                  * from parent ctx.
3414                  */
3415                 if (tctx->tlsext_ticket_key_cb)
3416                         {
3417                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3418                                                          &hctx, 1) < 0)
3419                                 {
3420                                 OPENSSL_free(senc);
3421                                 return -1;
3422                                 }
3423                         }
3424                 else
3425                         {
3426                         RAND_pseudo_bytes(iv, 16);
3427                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3428                                         tctx->tlsext_tick_aes_key, iv);
3429                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3430                                         tlsext_tick_md(), NULL);
3431                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3432                         }
3433
3434                 /* Ticket lifetime hint (advisory only):
3435                  * We leave this unspecified for resumed session (for simplicity),
3436                  * and guess that tickets for new sessions will live as long
3437                  * as their sessions. */
3438                 l2n(s->hit ? 0 : s->session->timeout, p);
3439
3440                 /* Skip ticket length for now */
3441                 p += 2;
3442                 /* Output key name */
3443                 macstart = p;
3444                 memcpy(p, key_name, 16);
3445                 p += 16;
3446                 /* output IV */
3447                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3448                 p += EVP_CIPHER_CTX_iv_length(&ctx);
3449                 /* Encrypt session data */
3450                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3451                 p += len;
3452                 EVP_EncryptFinal(&ctx, p, &len);
3453                 p += len;
3454                 EVP_CIPHER_CTX_cleanup(&ctx);
3455
3456                 HMAC_Update(&hctx, macstar