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