Remove "#if 0" code
[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 &= ~TLS1_FLAGS_SKIP_CERT_VERIFY;
304                         s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
305                         /* Should have been reset by ssl3_get_finished, too. */
306                         s->s3->change_cipher_spec = 0;
307
308                         if (s->state != SSL_ST_RENEGOTIATE)
309                                 {
310                                 /* Ok, we now need to push on a buffering BIO so that
311                                  * the output is sent in a way that TCP likes :-)
312                                  */
313                                 if (!ssl_init_wbio_buffer(s,1)) { ret= -1; goto end; }
314                                 
315                                 ssl3_init_finished_mac(s);
316                                 s->state=SSL3_ST_SR_CLNT_HELLO_A;
317                                 s->ctx->stats.sess_accept++;
318                                 }
319                         else if (!s->s3->send_connection_binding &&
320                                 !(s->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
321                                 {
322                                 /* Server attempting to renegotiate with
323                                  * client that doesn't support secure
324                                  * renegotiation.
325                                  */
326                                 SSLerr(SSL_F_SSL3_ACCEPT, SSL_R_UNSAFE_LEGACY_RENEGOTIATION_DISABLED);
327                                 ssl3_send_alert(s,SSL3_AL_FATAL,SSL_AD_HANDSHAKE_FAILURE);
328                                 ret = -1;
329                                 goto end;
330                                 }
331                         else
332                                 {
333                                 /* s->state == SSL_ST_RENEGOTIATE,
334                                  * we will just send a HelloRequest */
335                                 s->ctx->stats.sess_accept_renegotiate++;
336                                 s->state=SSL3_ST_SW_HELLO_REQ_A;
337                                 }
338                         break;
339
340                 case SSL3_ST_SW_HELLO_REQ_A:
341                 case SSL3_ST_SW_HELLO_REQ_B:
342
343                         s->shutdown=0;
344                         ret=ssl3_send_hello_request(s);
345                         if (ret <= 0) goto end;
346                         s->s3->tmp.next_state=SSL3_ST_SW_HELLO_REQ_C;
347                         s->state=SSL3_ST_SW_FLUSH;
348                         s->init_num=0;
349
350                         ssl3_init_finished_mac(s);
351                         break;
352
353                 case SSL3_ST_SW_HELLO_REQ_C:
354                         s->state=SSL_ST_OK;
355                         break;
356
357                 case SSL3_ST_SR_CLNT_HELLO_A:
358                 case SSL3_ST_SR_CLNT_HELLO_B:
359                 case SSL3_ST_SR_CLNT_HELLO_C:
360
361                         s->shutdown=0;
362                         ret=ssl3_get_client_hello(s);
363                         if (ret <= 0) goto end;
364 #ifndef OPENSSL_NO_SRP
365                         s->state = SSL3_ST_SR_CLNT_HELLO_D;
366                 case SSL3_ST_SR_CLNT_HELLO_D:
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_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 (SSL_USE_SIGALGS(s))
630                                 {
631                                 s->state=SSL3_ST_SR_CERT_VRFY_A;
632                                 s->init_num=0;
633                                 if (!s->session->peer)
634                                         break;
635                                 /* For sigalgs 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
892         if (s->state == SSL3_ST_SW_HELLO_REQ_A)
893                 {
894                 ssl_set_handshake_header(s, SSL3_MT_HELLO_REQUEST, 0);
895                 s->state=SSL3_ST_SW_HELLO_REQ_B;
896                 }
897
898         /* SSL3_ST_SW_HELLO_REQ_B */
899         return ssl_do_write(s);
900         }
901
902 int ssl3_check_client_hello(SSL *s)
903         {
904         int ok;
905         long n;
906
907         /* this function is called when we really expect a Certificate message,
908          * so permit appropriate message length */
909         n=s->method->ssl_get_message(s,
910                 SSL3_ST_SR_CERT_A,
911                 SSL3_ST_SR_CERT_B,
912                 -1,
913                 s->max_cert_list,
914                 &ok);
915         if (!ok) return((int)n);
916         s->s3->tmp.reuse_message = 1;
917         if (s->s3->tmp.message_type == SSL3_MT_CLIENT_HELLO)
918                 {
919                 /* We only allow the client to restart the handshake once per
920                  * negotiation. */
921                 if (s->s3->flags & SSL3_FLAGS_SGC_RESTART_DONE)
922                         {
923                         SSLerr(SSL_F_SSL3_CHECK_CLIENT_HELLO, SSL_R_MULTIPLE_SGC_RESTARTS);
924                         return -1;
925                         }
926                 /* Throw away what we have done so far in the current handshake,
927                  * which will now be aborted. (A full SSL_clear would be too much.) */
928 #ifndef OPENSSL_NO_DH
929                 if (s->s3->tmp.dh != NULL)
930                         {
931                         DH_free(s->s3->tmp.dh);
932                         s->s3->tmp.dh = NULL;
933                         }
934 #endif
935 #ifndef OPENSSL_NO_ECDH
936                 if (s->s3->tmp.ecdh != NULL)
937                         {
938                         EC_KEY_free(s->s3->tmp.ecdh);
939                         s->s3->tmp.ecdh = NULL;
940                         }
941 #endif
942                 s->s3->flags |= SSL3_FLAGS_SGC_RESTART_DONE;
943                 return 2;
944                 }
945         return 1;
946 }
947
948 int ssl3_get_client_hello(SSL *s)
949         {
950         int i,j,ok,al=SSL_AD_INTERNAL_ERROR,ret= -1;
951         unsigned int cookie_len;
952         long n;
953         unsigned long id;
954         unsigned char *p,*d;
955         SSL_CIPHER *c;
956 #ifndef OPENSSL_NO_COMP
957         unsigned char *q;
958         SSL_COMP *comp=NULL;
959 #endif
960         STACK_OF(SSL_CIPHER) *ciphers=NULL;
961
962         if (s->state == SSL3_ST_SR_CLNT_HELLO_C && !s->first_packet)
963                 goto retry_cert;
964
965         /* We do this so that we will respond with our native type.
966          * If we are TLSv1 and we get SSLv3, we will respond with TLSv1,
967          * This down switching should be handled by a different method.
968          * If we are SSLv3, we will respond with SSLv3, even if prompted with
969          * TLSv1.
970          */
971         if (s->state == SSL3_ST_SR_CLNT_HELLO_A
972                 )
973                 {
974                 s->state=SSL3_ST_SR_CLNT_HELLO_B;
975                 }
976         s->first_packet=1;
977         n=s->method->ssl_get_message(s,
978                 SSL3_ST_SR_CLNT_HELLO_B,
979                 SSL3_ST_SR_CLNT_HELLO_C,
980                 SSL3_MT_CLIENT_HELLO,
981                 SSL3_RT_MAX_PLAIN_LENGTH,
982                 &ok);
983
984         if (!ok) return((int)n);
985         s->first_packet=0;
986         d=p=(unsigned char *)s->init_msg;
987
988         /* use version from inside client hello, not from record header
989          * (may differ: see RFC 2246, Appendix E, second paragraph) */
990         s->client_version=(((int)p[0])<<8)|(int)p[1];
991         p+=2;
992
993         if (SSL_IS_DTLS(s)  ?   (s->client_version > s->version &&
994                                  s->method->version != DTLS_ANY_VERSION)
995                             :   (s->client_version < s->version))
996                 {
997                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
998                 if ((s->client_version>>8) == SSL3_VERSION_MAJOR &&
999                         !s->enc_write_ctx && !s->write_hash)
1000                         {
1001                         /* similar to ssl3_get_record, send alert using remote version number */
1002                         s->version = s->client_version;
1003                         }
1004                 al = SSL_AD_PROTOCOL_VERSION;
1005                 goto f_err;
1006                 }
1007
1008         /* If we require cookies and this ClientHello doesn't
1009          * contain one, just return since we do not want to
1010          * allocate any memory yet. So check cookie length...
1011          */
1012         if (SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE)
1013                 {
1014                 unsigned int session_length, cookie_length;
1015                 
1016                 session_length = *(p + SSL3_RANDOM_SIZE);
1017                 cookie_length = *(p + SSL3_RANDOM_SIZE + session_length + 1);
1018
1019                 if (cookie_length == 0)
1020                         return 1;
1021                 }
1022
1023         /* load the client random */
1024         memcpy(s->s3->client_random,p,SSL3_RANDOM_SIZE);
1025         p+=SSL3_RANDOM_SIZE;
1026
1027         /* get the session-id */
1028         j= *(p++);
1029
1030         s->hit=0;
1031         /* Versions before 0.9.7 always allow clients to resume sessions in renegotiation.
1032          * 0.9.7 and later allow this by default, but optionally ignore resumption requests
1033          * with flag SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION (it's a new flag rather
1034          * than a change to default behavior so that applications relying on this for security
1035          * won't even compile against older library versions).
1036          *
1037          * 1.0.1 and later also have a function SSL_renegotiate_abbreviated() to request
1038          * renegotiation but not a new session (s->new_session remains unset): for servers,
1039          * this essentially just means that the SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION
1040          * setting will be ignored.
1041          */
1042         if ((s->new_session && (s->options & SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION)))
1043                 {
1044                 if (!ssl_get_new_session(s,1))
1045                         goto err;
1046                 }
1047         else
1048                 {
1049                 i=ssl_get_prev_session(s, p, j, d + n);
1050                 /*
1051                  * Only resume if the session's version matches the negotiated
1052                  * version.
1053                  * RFC 5246 does not provide much useful advice on resumption
1054                  * with a different protocol version. It doesn't forbid it but
1055                  * the sanity of such behaviour would be questionable.
1056                  * In practice, clients do not accept a version mismatch and
1057                  * will abort the handshake with an error.
1058                  */
1059                 if (i == 1 && s->version == s->session->ssl_version)
1060                         { /* previous session */
1061                         s->hit=1;
1062                         }
1063                 else if (i == -1)
1064                         goto err;
1065                 else /* i == 0 */
1066                         {
1067                         if (!ssl_get_new_session(s,1))
1068                                 goto err;
1069                         }
1070                 }
1071
1072         p+=j;
1073
1074         if (SSL_IS_DTLS(s))
1075                 {
1076                 /* cookie stuff */
1077                 cookie_len = *(p++);
1078
1079                 /* 
1080                  * The ClientHello may contain a cookie even if the
1081                  * HelloVerify message has not been sent--make sure that it
1082                  * does not cause an overflow.
1083                  */
1084                 if ( cookie_len > sizeof(s->d1->rcvd_cookie))
1085                         {
1086                         /* too much data */
1087                         al = SSL_AD_DECODE_ERROR;
1088                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_COOKIE_MISMATCH);
1089                         goto f_err;
1090                         }
1091
1092                 /* verify the cookie if appropriate option is set. */
1093                 if ((SSL_get_options(s) & SSL_OP_COOKIE_EXCHANGE) &&
1094                         cookie_len > 0)
1095                         {
1096                         memcpy(s->d1->rcvd_cookie, p, cookie_len);
1097
1098                         if ( s->ctx->app_verify_cookie_cb != NULL)
1099                                 {
1100                                 if ( s->ctx->app_verify_cookie_cb(s, s->d1->rcvd_cookie,
1101                                         cookie_len) == 0)
1102                                         {
1103                                         al=SSL_AD_HANDSHAKE_FAILURE;
1104                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1105                                                 SSL_R_COOKIE_MISMATCH);
1106                                         goto f_err;
1107                                         }
1108                                 /* else cookie verification succeeded */
1109                                 }
1110                         else if ( memcmp(s->d1->rcvd_cookie, s->d1->cookie, 
1111                                                   s->d1->cookie_len) != 0) /* default verification */
1112                                 {
1113                                         al=SSL_AD_HANDSHAKE_FAILURE;
1114                                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, 
1115                                                 SSL_R_COOKIE_MISMATCH);
1116                                         goto f_err;
1117                                 }
1118                         /* Set to -2 so if successful we return 2 */
1119                         ret = -2;
1120                         }
1121
1122                 p += cookie_len;
1123                 if (s->method->version == DTLS_ANY_VERSION)
1124                         {
1125                         /* Select version to use */
1126                         if (s->client_version <= DTLS1_2_VERSION &&
1127                                 !(s->options & SSL_OP_NO_DTLSv1_2))
1128                                 {
1129                                 s->version = DTLS1_2_VERSION;
1130                                 s->method = DTLSv1_2_server_method();
1131                                 }
1132                         else if (tls1_suiteb(s))
1133                                 {
1134                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_ONLY_DTLS_1_2_ALLOWED_IN_SUITEB_MODE);
1135                                 s->version = s->client_version;
1136                                 al = SSL_AD_PROTOCOL_VERSION;
1137                                 goto f_err;
1138                                 }
1139                         else if (s->client_version <= DTLS1_VERSION &&
1140                                 !(s->options & SSL_OP_NO_DTLSv1))
1141                                 {
1142                                 s->version = DTLS1_VERSION;
1143                                 s->method = DTLSv1_server_method();
1144                                 }
1145                         else
1146                                 {
1147                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_WRONG_VERSION_NUMBER);
1148                                 s->version = s->client_version;
1149                                 al = SSL_AD_PROTOCOL_VERSION;
1150                                 goto f_err;
1151                                 }
1152                         s->session->ssl_version = s->version;
1153                         }
1154                 }
1155
1156         n2s(p,i);
1157         if ((i == 0) && (j != 0))
1158                 {
1159                 /* we need a cipher if we are not resuming a session */
1160                 al=SSL_AD_ILLEGAL_PARAMETER;
1161                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_SPECIFIED);
1162                 goto f_err;
1163                 }
1164         if ((p+i) >= (d+n))
1165                 {
1166                 /* not enough data */
1167                 al=SSL_AD_DECODE_ERROR;
1168                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1169                 goto f_err;
1170                 }
1171         if ((i > 0) && (ssl_bytes_to_cipher_list(s,p,i,&(ciphers))
1172                 == NULL))
1173                 {
1174                 goto err;
1175                 }
1176         p+=i;
1177
1178         /* If it is a hit, check that the cipher is in the list */
1179         if ((s->hit) && (i > 0))
1180                 {
1181                 j=0;
1182                 id=s->session->cipher->id;
1183
1184 #ifdef CIPHER_DEBUG
1185                 printf("client sent %d ciphers\n",sk_num(ciphers));
1186 #endif
1187                 for (i=0; i<sk_SSL_CIPHER_num(ciphers); i++)
1188                         {
1189                         c=sk_SSL_CIPHER_value(ciphers,i);
1190 #ifdef CIPHER_DEBUG
1191                         printf("client [%2d of %2d]:%s\n",
1192                                 i,sk_num(ciphers),SSL_CIPHER_get_name(c));
1193 #endif
1194                         if (c->id == id)
1195                                 {
1196                                 j=1;
1197                                 break;
1198                                 }
1199                         }
1200 /* Disabled because it can be used in a ciphersuite downgrade
1201  * attack: CVE-2010-4180.
1202  */
1203 #if 0
1204                 if (j == 0 && (s->options & SSL_OP_NETSCAPE_REUSE_CIPHER_CHANGE_BUG) && (sk_SSL_CIPHER_num(ciphers) == 1))
1205                         {
1206                         /* Special case as client bug workaround: the previously used cipher may
1207                          * not be in the current list, the client instead might be trying to
1208                          * continue using a cipher that before wasn't chosen due to server
1209                          * preferences.  We'll have to reject the connection if the cipher is not
1210                          * enabled, though. */
1211                         c = sk_SSL_CIPHER_value(ciphers, 0);
1212                         if (sk_SSL_CIPHER_find(SSL_get_ciphers(s), c) >= 0)
1213                                 {
1214                                 s->session->cipher = c;
1215                                 j = 1;
1216                                 }
1217                         }
1218 #endif
1219                 if (j == 0)
1220                         {
1221                         /* we need to have the cipher in the cipher
1222                          * list if we are asked to reuse it */
1223                         al=SSL_AD_ILLEGAL_PARAMETER;
1224                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_CIPHER_MISSING);
1225                         goto f_err;
1226                         }
1227                 }
1228
1229         /* compression */
1230         i= *(p++);
1231         if ((p+i) > (d+n))
1232                 {
1233                 /* not enough data */
1234                 al=SSL_AD_DECODE_ERROR;
1235                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_LENGTH_MISMATCH);
1236                 goto f_err;
1237                 }
1238 #ifndef OPENSSL_NO_COMP
1239         q=p;
1240 #endif
1241         for (j=0; j<i; j++)
1242                 {
1243                 if (p[j] == 0) break;
1244                 }
1245
1246         p+=i;
1247         if (j >= i)
1248                 {
1249                 /* no compress */
1250                 al=SSL_AD_DECODE_ERROR;
1251                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_COMPRESSION_SPECIFIED);
1252                 goto f_err;
1253                 }
1254
1255 #ifndef OPENSSL_NO_TLSEXT
1256         /* TLS extensions*/
1257         if (s->version >= SSL3_VERSION)
1258                 {
1259                 if (!ssl_parse_clienthello_tlsext(s,&p,d,n))
1260                         {
1261                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_PARSE_TLSEXT);
1262                         goto err;
1263                         }
1264                 }
1265
1266         /* Check if we want to use external pre-shared secret for this
1267          * handshake for not reused session only. We need to generate
1268          * server_random before calling tls_session_secret_cb in order to allow
1269          * SessionTicket processing to use it in key derivation. */
1270         {
1271                 unsigned char *pos;
1272                 pos=s->s3->server_random;
1273                 if (ssl_fill_hello_random(s, 1, pos, SSL3_RANDOM_SIZE) <= 0)
1274                         {
1275                         goto f_err;
1276                         }
1277         }
1278
1279         if (!s->hit && s->version >= TLS1_VERSION && s->tls_session_secret_cb)
1280                 {
1281                 SSL_CIPHER *pref_cipher=NULL;
1282
1283                 s->session->master_key_length=sizeof(s->session->master_key);
1284                 if(s->tls_session_secret_cb(s, s->session->master_key, &s->session->master_key_length,
1285                         ciphers, &pref_cipher, s->tls_session_secret_cb_arg))
1286                         {
1287                         s->hit=1;
1288                         s->session->ciphers=ciphers;
1289                         s->session->verify_result=X509_V_OK;
1290
1291                         ciphers=NULL;
1292
1293                         /* check if some cipher was preferred by call back */
1294                         pref_cipher=pref_cipher ? pref_cipher : ssl3_choose_cipher(s, s->session->ciphers, SSL_get_ciphers(s));
1295                         if (pref_cipher == NULL)
1296                                 {
1297                                 al=SSL_AD_HANDSHAKE_FAILURE;
1298                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1299                                 goto f_err;
1300                                 }
1301
1302                         s->session->cipher=pref_cipher;
1303
1304                         if (s->cipher_list)
1305                                 sk_SSL_CIPHER_free(s->cipher_list);
1306
1307                         if (s->cipher_list_by_id)
1308                                 sk_SSL_CIPHER_free(s->cipher_list_by_id);
1309
1310                         s->cipher_list = sk_SSL_CIPHER_dup(s->session->ciphers);
1311                         s->cipher_list_by_id = sk_SSL_CIPHER_dup(s->session->ciphers);
1312                         }
1313                 }
1314 #endif
1315
1316         /* Worst case, we will use the NULL compression, but if we have other
1317          * options, we will now look for them.  We have i-1 compression
1318          * algorithms from the client, starting at q. */
1319         s->s3->tmp.new_compression=NULL;
1320 #ifndef OPENSSL_NO_COMP
1321         /* This only happens if we have a cache hit */
1322         if (s->session->compress_meth != 0)
1323                 {
1324                 int m, comp_id = s->session->compress_meth;
1325                 /* Perform sanity checks on resumed compression algorithm */
1326                 /* Can't disable compression */
1327                 if (s->options & SSL_OP_NO_COMPRESSION)
1328                         {
1329                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1330                         goto f_err;
1331                         }
1332                 /* Look for resumed compression method */
1333                 for (m = 0; m < sk_SSL_COMP_num(s->ctx->comp_methods); m++)
1334                         {
1335                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1336                         if (comp_id == comp->id)
1337                                 {
1338                                 s->s3->tmp.new_compression=comp;
1339                                 break;
1340                                 }
1341                         }
1342                 if (s->s3->tmp.new_compression == NULL)
1343                         {
1344                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INVALID_COMPRESSION_ALGORITHM);
1345                         goto f_err;
1346                         }
1347                 /* Look for resumed method in compression list */
1348                 for (m = 0; m < i; m++)
1349                         {
1350                         if (q[m] == comp_id)
1351                                 break;
1352                         }
1353                 if (m >= i)
1354                         {
1355                         al=SSL_AD_ILLEGAL_PARAMETER;
1356                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_REQUIRED_COMPRESSSION_ALGORITHM_MISSING);
1357                         goto f_err;
1358                         }
1359                 }
1360         else if (s->hit)
1361                 comp = NULL;
1362         else if (!(s->options & SSL_OP_NO_COMPRESSION) && s->ctx->comp_methods)
1363                 { /* See if we have a match */
1364                 int m,nn,o,v,done=0;
1365
1366                 nn=sk_SSL_COMP_num(s->ctx->comp_methods);
1367                 for (m=0; m<nn; m++)
1368                         {
1369                         comp=sk_SSL_COMP_value(s->ctx->comp_methods,m);
1370                         v=comp->id;
1371                         for (o=0; o<i; o++)
1372                                 {
1373                                 if (v == q[o])
1374                                         {
1375                                         done=1;
1376                                         break;
1377                                         }
1378                                 }
1379                         if (done) break;
1380                         }
1381                 if (done)
1382                         s->s3->tmp.new_compression=comp;
1383                 else
1384                         comp=NULL;
1385                 }
1386 #else
1387         /* If compression is disabled we'd better not try to resume a session
1388          * using compression.
1389          */
1390         if (s->session->compress_meth != 0)
1391                 {
1392                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_INCONSISTENT_COMPRESSION);
1393                 goto f_err;
1394                 }
1395 #endif
1396
1397         /* Given s->session->ciphers and SSL_get_ciphers, we must
1398          * pick a cipher */
1399
1400         if (!s->hit)
1401                 {
1402 #ifdef OPENSSL_NO_COMP
1403                 s->session->compress_meth=0;
1404 #else
1405                 s->session->compress_meth=(comp == NULL)?0:comp->id;
1406 #endif
1407                 if (s->session->ciphers != NULL)
1408                         sk_SSL_CIPHER_free(s->session->ciphers);
1409                 s->session->ciphers=ciphers;
1410                 if (ciphers == NULL)
1411                         {
1412                         al=SSL_AD_ILLEGAL_PARAMETER;
1413                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_CIPHERS_PASSED);
1414                         goto f_err;
1415                         }
1416                 ciphers=NULL;
1417                 if (!tls1_set_server_sigalgs(s))
1418                         {
1419                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1420                         goto err;
1421                         }
1422                 /* Let cert callback update server certificates if required */
1423                 retry_cert:             
1424                 if (s->cert->cert_cb)
1425                         {
1426                         int rv = s->cert->cert_cb(s, s->cert->cert_cb_arg);
1427                         if (rv == 0)
1428                                 {
1429                                 al=SSL_AD_INTERNAL_ERROR;
1430                                 SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_CERT_CB_ERROR);
1431                                 goto f_err;
1432                                 }
1433                         if (rv < 0)
1434                                 {
1435                                 s->rwstate=SSL_X509_LOOKUP;
1436                                 return -1;
1437                                 }
1438                         s->rwstate = SSL_NOTHING;
1439                         }
1440                 c=ssl3_choose_cipher(s,s->session->ciphers,
1441                                      SSL_get_ciphers(s));
1442
1443                 if (c == NULL)
1444                         {
1445                         al=SSL_AD_HANDSHAKE_FAILURE;
1446                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO,SSL_R_NO_SHARED_CIPHER);
1447                         goto f_err;
1448                         }
1449                 s->s3->tmp.new_cipher=c;
1450                 }
1451         else
1452                 {
1453                 /* Session-id reuse */
1454 #ifdef REUSE_CIPHER_BUG
1455                 STACK_OF(SSL_CIPHER) *sk;
1456                 SSL_CIPHER *nc=NULL;
1457                 SSL_CIPHER *ec=NULL;
1458
1459                 if (s->options & SSL_OP_NETSCAPE_DEMO_CIPHER_CHANGE_BUG)
1460                         {
1461                         sk=s->session->ciphers;
1462                         for (i=0; i<sk_SSL_CIPHER_num(sk); i++)
1463                                 {
1464                                 c=sk_SSL_CIPHER_value(sk,i);
1465                                 if (c->algorithm_enc & SSL_eNULL)
1466                                         nc=c;
1467                                 if (SSL_C_IS_EXPORT(c))
1468                                         ec=c;
1469                                 }
1470                         if (nc != NULL)
1471                                 s->s3->tmp.new_cipher=nc;
1472                         else if (ec != NULL)
1473                                 s->s3->tmp.new_cipher=ec;
1474                         else
1475                                 s->s3->tmp.new_cipher=s->session->cipher;
1476                         }
1477                 else
1478 #endif
1479                 s->s3->tmp.new_cipher=s->session->cipher;
1480                 }
1481
1482         if (!SSL_USE_SIGALGS(s) || !(s->verify_mode & SSL_VERIFY_PEER))
1483                 {
1484                 if (!ssl3_digest_cached_records(s))
1485                         goto f_err;
1486                 }
1487         
1488         /* we now have the following setup. 
1489          * client_random
1490          * cipher_list          - our prefered list of ciphers
1491          * ciphers              - the clients prefered list of ciphers
1492          * compression          - basically ignored right now
1493          * ssl version is set   - sslv3
1494          * s->session           - The ssl session has been setup.
1495          * s->hit               - session reuse flag
1496          * s->tmp.new_cipher    - the new cipher to use.
1497          */
1498
1499         /* Handles TLS extensions that we couldn't check earlier */
1500         if (s->version >= SSL3_VERSION)
1501                 {
1502                 if (ssl_check_clienthello_tlsext_late(s) <= 0)
1503                         {
1504                         SSLerr(SSL_F_SSL3_GET_CLIENT_HELLO, SSL_R_CLIENTHELLO_TLSEXT);
1505                         goto err;
1506                         }
1507                 }
1508
1509         if (ret < 0) ret=-ret;
1510         if (0)
1511                 {
1512 f_err:
1513                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1514                 }
1515 err:
1516         if (ciphers != NULL) sk_SSL_CIPHER_free(ciphers);
1517         return ret < 0 ? -1 : ret;
1518         }
1519
1520 int ssl3_send_server_hello(SSL *s)
1521         {
1522         unsigned char *buf;
1523         unsigned char *p,*d;
1524         int i,sl;
1525         int al = 0;
1526         unsigned long l;
1527
1528         if (s->state == SSL3_ST_SW_SRVR_HELLO_A)
1529                 {
1530                 buf=(unsigned char *)s->init_buf->data;
1531 #ifdef OPENSSL_NO_TLSEXT
1532                 p=s->s3->server_random;
1533                 if (ssl_fill_hello_random(s, 1, p, SSL3_RANDOM_SIZE) <= 0)
1534                         return -1;
1535 #endif
1536                 /* Do the message type and length last */
1537                 d=p= ssl_handshake_start(s);
1538
1539                 *(p++)=s->version>>8;
1540                 *(p++)=s->version&0xff;
1541
1542                 /* Random stuff */
1543                 memcpy(p,s->s3->server_random,SSL3_RANDOM_SIZE);
1544                 p+=SSL3_RANDOM_SIZE;
1545
1546                 /* There are several cases for the session ID to send
1547                  * back in the server hello:
1548                  * - For session reuse from the session cache,
1549                  *   we send back the old session ID.
1550                  * - If stateless session reuse (using a session ticket)
1551                  *   is successful, we send back the client's "session ID"
1552                  *   (which doesn't actually identify the session).
1553                  * - If it is a new session, we send back the new
1554                  *   session ID.
1555                  * - However, if we want the new session to be single-use,
1556                  *   we send back a 0-length session ID.
1557                  * s->hit is non-zero in either case of session reuse,
1558                  * so the following won't overwrite an ID that we're supposed
1559                  * to send back.
1560                  */
1561                 if (!(s->ctx->session_cache_mode & SSL_SESS_CACHE_SERVER)
1562                         && !s->hit)
1563                         s->session->session_id_length=0;
1564
1565                 sl=s->session->session_id_length;
1566                 if (sl > (int)sizeof(s->session->session_id))
1567                         {
1568                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO, ERR_R_INTERNAL_ERROR);
1569                         return -1;
1570                         }
1571                 *(p++)=sl;
1572                 memcpy(p,s->session->session_id,sl);
1573                 p+=sl;
1574
1575                 /* put the cipher */
1576                 i=ssl3_put_cipher_by_char(s->s3->tmp.new_cipher,p);
1577                 p+=i;
1578
1579                 /* put the compression method */
1580 #ifdef OPENSSL_NO_COMP
1581                         *(p++)=0;
1582 #else
1583                 if (s->s3->tmp.new_compression == NULL)
1584                         *(p++)=0;
1585                 else
1586                         *(p++)=s->s3->tmp.new_compression->id;
1587 #endif
1588 #ifndef OPENSSL_NO_TLSEXT
1589                 if (ssl_prepare_serverhello_tlsext(s) <= 0)
1590                         {
1591                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,SSL_R_SERVERHELLO_TLSEXT);
1592                         return -1;
1593                         }
1594                 if ((p = ssl_add_serverhello_tlsext(s, p, buf+SSL3_RT_MAX_PLAIN_LENGTH, &al)) == NULL)
1595                         {
1596                         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1597                         SSLerr(SSL_F_SSL3_SEND_SERVER_HELLO,ERR_R_INTERNAL_ERROR);
1598                         return -1;
1599                         }
1600 #endif
1601                 /* do the header */
1602                 l=(p-d);
1603                 ssl_set_handshake_header(s, SSL3_MT_SERVER_HELLO, l);
1604                 s->state=SSL3_ST_SW_SRVR_HELLO_B;
1605                 }
1606
1607         /* SSL3_ST_SW_SRVR_HELLO_B */
1608         return ssl_do_write(s);
1609         }
1610
1611 int ssl3_send_server_done(SSL *s)
1612         {
1613
1614         if (s->state == SSL3_ST_SW_SRVR_DONE_A)
1615                 {
1616                 ssl_set_handshake_header(s, SSL3_MT_SERVER_DONE, 0);
1617                 s->state = SSL3_ST_SW_SRVR_DONE_B;
1618                 }
1619
1620         /* SSL3_ST_SW_SRVR_DONE_B */
1621         return ssl_do_write(s);
1622         }
1623
1624 int ssl3_send_server_key_exchange(SSL *s)
1625         {
1626 #ifndef OPENSSL_NO_RSA
1627         unsigned char *q;
1628         int j,num;
1629         RSA *rsa;
1630         unsigned char md_buf[MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH];
1631         unsigned int u;
1632 #endif
1633 #ifndef OPENSSL_NO_DH
1634         DH *dh=NULL,*dhp;
1635 #endif
1636 #ifndef OPENSSL_NO_ECDH
1637         EC_KEY *ecdh=NULL, *ecdhp;
1638         unsigned char *encodedPoint = NULL;
1639         int encodedlen = 0;
1640         int curve_id = 0;
1641         BN_CTX *bn_ctx = NULL; 
1642 #endif
1643         EVP_PKEY *pkey;
1644         const EVP_MD *md = NULL;
1645         unsigned char *p,*d;
1646         int al,i;
1647         unsigned long type;
1648         int n;
1649         CERT *cert;
1650         BIGNUM *r[4];
1651         int nr[4],kn;
1652         BUF_MEM *buf;
1653         EVP_MD_CTX md_ctx;
1654
1655         EVP_MD_CTX_init(&md_ctx);
1656         if (s->state == SSL3_ST_SW_KEY_EXCH_A)
1657                 {
1658                 type=s->s3->tmp.new_cipher->algorithm_mkey;
1659                 cert=s->cert;
1660
1661                 buf=s->init_buf;
1662
1663                 r[0]=r[1]=r[2]=r[3]=NULL;
1664                 n=0;
1665 #ifndef OPENSSL_NO_RSA
1666                 if (type & SSL_kRSA)
1667                         {
1668                         rsa=cert->rsa_tmp;
1669                         if ((rsa == NULL) && (s->cert->rsa_tmp_cb != NULL))
1670                                 {
1671                                 rsa=s->cert->rsa_tmp_cb(s,
1672                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1673                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1674                                 if(rsa == NULL)
1675                                 {
1676                                         al=SSL_AD_HANDSHAKE_FAILURE;
1677                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ERROR_GENERATING_TMP_RSA_KEY);
1678                                         goto f_err;
1679                                 }
1680                                 RSA_up_ref(rsa);
1681                                 cert->rsa_tmp=rsa;
1682                                 }
1683                         if (rsa == NULL)
1684                                 {
1685                                 al=SSL_AD_HANDSHAKE_FAILURE;
1686                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_KEY);
1687                                 goto f_err;
1688                                 }
1689                         r[0]=rsa->n;
1690                         r[1]=rsa->e;
1691                         s->s3->tmp.use_rsa_tmp=1;
1692                         }
1693                 else
1694 #endif
1695 #ifndef OPENSSL_NO_DH
1696                         if (type & SSL_kEDH)
1697                         {
1698                         dhp=cert->dh_tmp;
1699                         if ((dhp == NULL) && (s->cert->dh_tmp_cb != NULL))
1700                                 dhp=s->cert->dh_tmp_cb(s,
1701                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1702                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1703                         if (dhp == NULL)
1704                                 {
1705                                 al=SSL_AD_HANDSHAKE_FAILURE;
1706                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
1707                                 goto f_err;
1708                                 }
1709
1710                         if (s->s3->tmp.dh != NULL)
1711                                 {
1712                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1713                                 goto err;
1714                                 }
1715
1716                         if ((dh=DHparams_dup(dhp)) == NULL)
1717                                 {
1718                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1719                                 goto err;
1720                                 }
1721
1722                         s->s3->tmp.dh=dh;
1723                         if ((dhp->pub_key == NULL ||
1724                              dhp->priv_key == NULL ||
1725                              (s->options & SSL_OP_SINGLE_DH_USE)))
1726                                 {
1727                                 if(!DH_generate_key(dh))
1728                                     {
1729                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,
1730                                            ERR_R_DH_LIB);
1731                                     goto err;
1732                                     }
1733                                 }
1734                         else
1735                                 {
1736                                 dh->pub_key=BN_dup(dhp->pub_key);
1737                                 dh->priv_key=BN_dup(dhp->priv_key);
1738                                 if ((dh->pub_key == NULL) ||
1739                                         (dh->priv_key == NULL))
1740                                         {
1741                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_DH_LIB);
1742                                         goto err;
1743                                         }
1744                                 }
1745                         r[0]=dh->p;
1746                         r[1]=dh->g;
1747                         r[2]=dh->pub_key;
1748                         }
1749                 else 
1750 #endif
1751 #ifndef OPENSSL_NO_ECDH
1752                         if (type & SSL_kEECDH)
1753                         {
1754                         const EC_GROUP *group;
1755
1756                         ecdhp=cert->ecdh_tmp;
1757                         if (s->cert->ecdh_tmp_auto)
1758                                 {
1759                                 /* Get NID of appropriate shared curve */
1760                                 int nid = tls1_shared_curve(s, -2);
1761                                 if (nid != NID_undef)
1762                                         ecdhp = EC_KEY_new_by_curve_name(nid);
1763                                 }
1764                         else if ((ecdhp == NULL) && s->cert->ecdh_tmp_cb)
1765                                 {
1766                                 ecdhp=s->cert->ecdh_tmp_cb(s,
1767                                       SSL_C_IS_EXPORT(s->s3->tmp.new_cipher),
1768                                       SSL_C_EXPORT_PKEYLENGTH(s->s3->tmp.new_cipher));
1769                                 }
1770                         if (ecdhp == NULL)
1771                                 {
1772                                 al=SSL_AD_HANDSHAKE_FAILURE;
1773                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
1774                                 goto f_err;
1775                                 }
1776
1777                         if (s->s3->tmp.ecdh != NULL)
1778                                 {
1779                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE, ERR_R_INTERNAL_ERROR);
1780                                 goto err;
1781                                 }
1782
1783                         /* Duplicate the ECDH structure. */
1784                         if (ecdhp == NULL)
1785                                 {
1786                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1787                                 goto err;
1788                                 }
1789                         if (s->cert->ecdh_tmp_auto)
1790                                 ecdh = ecdhp;
1791                         else if ((ecdh = EC_KEY_dup(ecdhp)) == NULL)
1792                                 {
1793                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1794                                 goto err;
1795                                 }
1796
1797                         s->s3->tmp.ecdh=ecdh;
1798                         if ((EC_KEY_get0_public_key(ecdh) == NULL) ||
1799                             (EC_KEY_get0_private_key(ecdh) == NULL) ||
1800                             (s->options & SSL_OP_SINGLE_ECDH_USE))
1801                                 {
1802                                 if(!EC_KEY_generate_key(ecdh))
1803                                     {
1804                                     SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1805                                     goto err;
1806                                     }
1807                                 }
1808
1809                         if (((group = EC_KEY_get0_group(ecdh)) == NULL) ||
1810                             (EC_KEY_get0_public_key(ecdh)  == NULL) ||
1811                             (EC_KEY_get0_private_key(ecdh) == NULL))
1812                                 {
1813                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1814                                 goto err;
1815                                 }
1816
1817                         if (SSL_C_IS_EXPORT(s->s3->tmp.new_cipher) &&
1818                             (EC_GROUP_get_degree(group) > 163)) 
1819                                 {
1820                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_ECGROUP_TOO_LARGE_FOR_CIPHER);
1821                                 goto err;
1822                                 }
1823
1824                         /* XXX: For now, we only support ephemeral ECDH
1825                          * keys over named (not generic) curves. For 
1826                          * supported named curves, curve_id is non-zero.
1827                          */
1828                         if ((curve_id = 
1829                             tls1_ec_nid2curve_id(EC_GROUP_get_curve_name(group)))
1830                             == 0)
1831                                 {
1832                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNSUPPORTED_ELLIPTIC_CURVE);
1833                                 goto err;
1834                                 }
1835
1836                         /* Encode the public key.
1837                          * First check the size of encoding and
1838                          * allocate memory accordingly.
1839                          */
1840                         encodedlen = EC_POINT_point2oct(group, 
1841                             EC_KEY_get0_public_key(ecdh),
1842                             POINT_CONVERSION_UNCOMPRESSED, 
1843                             NULL, 0, NULL);
1844
1845                         encodedPoint = (unsigned char *) 
1846                             OPENSSL_malloc(encodedlen*sizeof(unsigned char)); 
1847                         bn_ctx = BN_CTX_new();
1848                         if ((encodedPoint == NULL) || (bn_ctx == NULL))
1849                                 {
1850                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_MALLOC_FAILURE);
1851                                 goto err;
1852                                 }
1853
1854
1855                         encodedlen = EC_POINT_point2oct(group, 
1856                             EC_KEY_get0_public_key(ecdh), 
1857                             POINT_CONVERSION_UNCOMPRESSED, 
1858                             encodedPoint, encodedlen, bn_ctx);
1859
1860                         if (encodedlen == 0) 
1861                                 {
1862                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_ECDH_LIB);
1863                                 goto err;
1864                                 }
1865
1866                         BN_CTX_free(bn_ctx);  bn_ctx=NULL;
1867
1868                         /* XXX: For now, we only support named (not 
1869                          * generic) curves in ECDH ephemeral key exchanges.
1870                          * In this situation, we need four additional bytes
1871                          * to encode the entire ServerECDHParams
1872                          * structure. 
1873                          */
1874                         n = 4 + encodedlen;
1875
1876                         /* We'll generate the serverKeyExchange message
1877                          * explicitly so we can set these to NULLs
1878                          */
1879                         r[0]=NULL;
1880                         r[1]=NULL;
1881                         r[2]=NULL;
1882                         r[3]=NULL;
1883                         }
1884                 else 
1885 #endif /* !OPENSSL_NO_ECDH */
1886 #ifndef OPENSSL_NO_PSK
1887                         if (type & SSL_kPSK)
1888                                 {
1889                                 /* reserve size for record length and PSK identity hint*/
1890                                 n+=2+strlen(s->ctx->psk_identity_hint);
1891                                 }
1892                         else
1893 #endif /* !OPENSSL_NO_PSK */
1894 #ifndef OPENSSL_NO_SRP
1895                 if (type & SSL_kSRP)
1896                         {
1897                         if ((s->srp_ctx.N == NULL) ||
1898                                 (s->srp_ctx.g == NULL) ||
1899                                 (s->srp_ctx.s == NULL) ||
1900                                 (s->srp_ctx.B == NULL))
1901                                 {
1902                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_MISSING_SRP_PARAM);
1903                                 goto err;
1904                                 }
1905                         r[0]=s->srp_ctx.N;
1906                         r[1]=s->srp_ctx.g;
1907                         r[2]=s->srp_ctx.s;
1908                         r[3]=s->srp_ctx.B;
1909                         }
1910                 else 
1911 #endif
1912                         {
1913                         al=SSL_AD_HANDSHAKE_FAILURE;
1914                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_KEY_EXCHANGE_TYPE);
1915                         goto f_err;
1916                         }
1917                 for (i=0; i < 4 && r[i] != NULL; i++)
1918                         {
1919                         nr[i]=BN_num_bytes(r[i]);
1920 #ifndef OPENSSL_NO_SRP
1921                         if ((i == 2) && (type & SSL_kSRP))
1922                                 n+=1+nr[i];
1923                         else
1924 #endif
1925                         n+=2+nr[i];
1926                         }
1927
1928                 if (!(s->s3->tmp.new_cipher->algorithm_auth & (SSL_aNULL|SSL_aSRP))
1929                         && !(s->s3->tmp.new_cipher->algorithm_mkey & SSL_kPSK))
1930                         {
1931                         if ((pkey=ssl_get_sign_pkey(s,s->s3->tmp.new_cipher,&md))
1932                                 == NULL)
1933                                 {
1934                                 al=SSL_AD_DECODE_ERROR;
1935                                 goto f_err;
1936                                 }
1937                         kn=EVP_PKEY_size(pkey);
1938                         }
1939                 else
1940                         {
1941                         pkey=NULL;
1942                         kn=0;
1943                         }
1944
1945                 if (!BUF_MEM_grow_clean(buf,n+SSL_HM_HEADER_LENGTH(s)+kn))
1946                         {
1947                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_BUF);
1948                         goto err;
1949                         }
1950                 d = p = ssl_handshake_start(s);
1951
1952                 for (i=0; i < 4 && r[i] != NULL; i++)
1953                         {
1954 #ifndef OPENSSL_NO_SRP
1955                         if ((i == 2) && (type & SSL_kSRP))
1956                                 {
1957                                 *p = nr[i];
1958                                 p++;
1959                                 }
1960                         else
1961 #endif
1962                         s2n(nr[i],p);
1963                         BN_bn2bin(r[i],p);
1964                         p+=nr[i];
1965                         }
1966
1967 #ifndef OPENSSL_NO_ECDH
1968                 if (type & SSL_kEECDH) 
1969                         {
1970                         /* XXX: For now, we only support named (not generic) curves.
1971                          * In this situation, the serverKeyExchange message has:
1972                          * [1 byte CurveType], [2 byte CurveName]
1973                          * [1 byte length of encoded point], followed by
1974                          * the actual encoded point itself
1975                          */
1976                         *p = NAMED_CURVE_TYPE;
1977                         p += 1;
1978                         *p = 0;
1979                         p += 1;
1980                         *p = curve_id;
1981                         p += 1;
1982                         *p = encodedlen;
1983                         p += 1;
1984                         memcpy((unsigned char*)p, 
1985                             (unsigned char *)encodedPoint, 
1986                             encodedlen);
1987                         OPENSSL_free(encodedPoint);
1988                         encodedPoint = NULL;
1989                         p += encodedlen;
1990                         }
1991 #endif
1992
1993 #ifndef OPENSSL_NO_PSK
1994                 if (type & SSL_kPSK)
1995                         {
1996                         /* copy PSK identity hint */
1997                         s2n(strlen(s->ctx->psk_identity_hint), p); 
1998                         strncpy((char *)p, s->ctx->psk_identity_hint, strlen(s->ctx->psk_identity_hint));
1999                         p+=strlen(s->ctx->psk_identity_hint);
2000                         }
2001 #endif
2002
2003                 /* not anonymous */
2004                 if (pkey != NULL)
2005                         {
2006                         /* n is the length of the params, they start at &(d[4])
2007                          * and p points to the space at the end. */
2008 #ifndef OPENSSL_NO_RSA
2009                         if (pkey->type == EVP_PKEY_RSA && !SSL_USE_SIGALGS(s))
2010                                 {
2011                                 q=md_buf;
2012                                 j=0;
2013                                 for (num=2; num > 0; num--)
2014                                         {
2015                                         EVP_MD_CTX_set_flags(&md_ctx,
2016                                                 EVP_MD_CTX_FLAG_NON_FIPS_ALLOW);
2017                                         EVP_DigestInit_ex(&md_ctx,(num == 2)
2018                                                 ?s->ctx->md5:s->ctx->sha1, NULL);
2019                                         EVP_DigestUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2020                                         EVP_DigestUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2021                                         EVP_DigestUpdate(&md_ctx,d,n);
2022                                         EVP_DigestFinal_ex(&md_ctx,q,
2023                                                 (unsigned int *)&i);
2024                                         q+=i;
2025                                         j+=i;
2026                                         }
2027                                 if (RSA_sign(NID_md5_sha1, md_buf, j,
2028                                         &(p[2]), &u, pkey->pkey.rsa) <= 0)
2029                                         {
2030                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_RSA);
2031                                         goto err;
2032                                         }
2033                                 s2n(u,p);
2034                                 n+=u+2;
2035                                 }
2036                         else
2037 #endif
2038                         if (md)
2039                                 {
2040                                 /* send signature algorithm */
2041                                 if (SSL_USE_SIGALGS(s))
2042                                         {
2043                                         if (!tls12_get_sigandhash(p, pkey, md))
2044                                                 {
2045                                                 /* Should never happen */
2046                                                 al=SSL_AD_INTERNAL_ERROR;
2047                                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2048                                                 goto f_err;
2049                                                 }
2050                                         p+=2;
2051                                         }
2052 #ifdef SSL_DEBUG
2053                                 fprintf(stderr, "Using hash %s\n",
2054                                                         EVP_MD_name(md));
2055 #endif
2056                                 EVP_SignInit_ex(&md_ctx, md, NULL);
2057                                 EVP_SignUpdate(&md_ctx,&(s->s3->client_random[0]),SSL3_RANDOM_SIZE);
2058                                 EVP_SignUpdate(&md_ctx,&(s->s3->server_random[0]),SSL3_RANDOM_SIZE);
2059                                 EVP_SignUpdate(&md_ctx,d,n);
2060                                 if (!EVP_SignFinal(&md_ctx,&(p[2]),
2061                                         (unsigned int *)&i,pkey))
2062                                         {
2063                                         SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,ERR_LIB_EVP);
2064                                         goto err;
2065                                         }
2066                                 s2n(i,p);
2067                                 n+=i+2;
2068                                 if (SSL_USE_SIGALGS(s))
2069                                         n+= 2;
2070                                 }
2071                         else
2072                                 {
2073                                 /* Is this error check actually needed? */
2074                                 al=SSL_AD_HANDSHAKE_FAILURE;
2075                                 SSLerr(SSL_F_SSL3_SEND_SERVER_KEY_EXCHANGE,SSL_R_UNKNOWN_PKEY_TYPE);
2076                                 goto f_err;
2077                                 }
2078                         }
2079
2080                 ssl_set_handshake_header(s, SSL3_MT_SERVER_KEY_EXCHANGE, n);
2081                 }
2082
2083         s->state = SSL3_ST_SW_KEY_EXCH_B;
2084         EVP_MD_CTX_cleanup(&md_ctx);
2085         return ssl_do_write(s);
2086 f_err:
2087         ssl3_send_alert(s,SSL3_AL_FATAL,al);
2088 err:
2089 #ifndef OPENSSL_NO_ECDH
2090         if (encodedPoint != NULL) OPENSSL_free(encodedPoint);
2091         BN_CTX_free(bn_ctx);
2092 #endif
2093         EVP_MD_CTX_cleanup(&md_ctx);
2094         return(-1);
2095         }
2096
2097 int ssl3_send_certificate_request(SSL *s)
2098         {
2099         unsigned char *p,*d;
2100         int i,j,nl,off,n;
2101         STACK_OF(X509_NAME) *sk=NULL;
2102         X509_NAME *name;
2103         BUF_MEM *buf;
2104
2105         if (s->state == SSL3_ST_SW_CERT_REQ_A)
2106                 {
2107                 buf=s->init_buf;
2108
2109                 d=p=ssl_handshake_start(s);
2110
2111                 /* get the list of acceptable cert types */
2112                 p++;
2113                 n=ssl3_get_req_cert_type(s,p);
2114                 d[0]=n;
2115                 p+=n;
2116                 n++;
2117
2118                 if (SSL_USE_SIGALGS(s))
2119                         {
2120                         const unsigned char *psigs;
2121                         nl = tls12_get_psigalgs(s, &psigs);
2122                         s2n(nl, p);
2123                         memcpy(p, psigs, nl);
2124                         p += nl;
2125                         n += nl + 2;
2126                         }
2127
2128                 off=n;
2129                 p+=2;
2130                 n+=2;
2131
2132                 sk=SSL_get_client_CA_list(s);
2133                 nl=0;
2134                 if (sk != NULL)
2135                         {
2136                         for (i=0; i<sk_X509_NAME_num(sk); i++)
2137                                 {
2138                                 name=sk_X509_NAME_value(sk,i);
2139                                 j=i2d_X509_NAME(name,NULL);
2140                                 if (!BUF_MEM_grow_clean(buf,SSL_HM_HEADER_LENGTH(s)+n+j+2))
2141                                         {
2142                                         SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2143                                         goto err;
2144                                         }
2145                                 p = ssl_handshake_start(s) + n;
2146                                 if (!(s->options & SSL_OP_NETSCAPE_CA_DN_BUG))
2147                                         {
2148                                         s2n(j,p);
2149                                         i2d_X509_NAME(name,&p);
2150                                         n+=2+j;
2151                                         nl+=2+j;
2152                                         }
2153                                 else
2154                                         {
2155                                         d=p;
2156                                         i2d_X509_NAME(name,&p);
2157                                         j-=2; s2n(j,d); j+=2;
2158                                         n+=j;
2159                                         nl+=j;
2160                                         }
2161                                 }
2162                         }
2163                 /* else no CA names */
2164                 p = ssl_handshake_start(s) + off;
2165                 s2n(nl,p);
2166
2167                 ssl_set_handshake_header(s, SSL3_MT_CERTIFICATE_REQUEST, n);
2168
2169 #ifdef NETSCAPE_HANG_BUG
2170                 if (!SSL_IS_DTLS(s))
2171                         {
2172                         if (!BUF_MEM_grow_clean(buf, s->init_num + 4))
2173                                 {
2174                                 SSLerr(SSL_F_SSL3_SEND_CERTIFICATE_REQUEST,ERR_R_BUF_LIB);
2175                                 goto err;
2176                                 }
2177                         p=(unsigned char *)s->init_buf->data + s->init_num;
2178                         /* do the header */
2179                         *(p++)=SSL3_MT_SERVER_DONE;
2180                         *(p++)=0;
2181                         *(p++)=0;
2182                         *(p++)=0;
2183                         s->init_num += 4;
2184                         }
2185 #endif
2186
2187                 s->state = SSL3_ST_SW_CERT_REQ_B;
2188                 }
2189
2190         /* SSL3_ST_SW_CERT_REQ_B */
2191         return ssl_do_write(s);
2192 err:
2193         return(-1);
2194         }
2195
2196 int ssl3_get_client_key_exchange(SSL *s)
2197         {
2198         int i,al,ok;
2199         long n;
2200         unsigned long alg_k;
2201         unsigned char *p;
2202 #ifndef OPENSSL_NO_RSA
2203         RSA *rsa=NULL;
2204         EVP_PKEY *pkey=NULL;
2205 #endif
2206 #ifndef OPENSSL_NO_DH
2207         BIGNUM *pub=NULL;
2208         DH *dh_srvr, *dh_clnt = NULL;
2209 #endif
2210 #ifndef OPENSSL_NO_KRB5
2211         KSSL_ERR kssl_err;
2212 #endif /* OPENSSL_NO_KRB5 */
2213
2214 #ifndef OPENSSL_NO_ECDH
2215         EC_KEY *srvr_ecdh = NULL;
2216         EVP_PKEY *clnt_pub_pkey = NULL;
2217         EC_POINT *clnt_ecpoint = NULL;
2218         BN_CTX *bn_ctx = NULL; 
2219 #endif
2220
2221         n=s->method->ssl_get_message(s,
2222                 SSL3_ST_SR_KEY_EXCH_A,
2223                 SSL3_ST_SR_KEY_EXCH_B,
2224                 SSL3_MT_CLIENT_KEY_EXCHANGE,
2225                 2048, /* ??? */
2226                 &ok);
2227
2228         if (!ok) return((int)n);
2229         p=(unsigned char *)s->init_msg;
2230
2231         alg_k=s->s3->tmp.new_cipher->algorithm_mkey;
2232
2233 #ifndef OPENSSL_NO_RSA
2234         if (alg_k & SSL_kRSA)
2235                 {
2236                 unsigned char rand_premaster_secret[SSL_MAX_MASTER_KEY_LENGTH];
2237                 int decrypt_len;
2238                 unsigned char decrypt_good, version_good;
2239
2240                 /* FIX THIS UP EAY EAY EAY EAY */
2241                 if (s->s3->tmp.use_rsa_tmp)
2242                         {
2243                         if ((s->cert != NULL) && (s->cert->rsa_tmp != NULL))
2244                                 rsa=s->cert->rsa_tmp;
2245                         /* Don't do a callback because rsa_tmp should
2246                          * be sent already */
2247                         if (rsa == NULL)
2248                                 {
2249                                 al=SSL_AD_HANDSHAKE_FAILURE;
2250                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_RSA_PKEY);
2251                                 goto f_err;
2252
2253                                 }
2254                         }
2255                 else
2256                         {
2257                         pkey=s->cert->pkeys[SSL_PKEY_RSA_ENC].privatekey;
2258                         if (    (pkey == NULL) ||
2259                                 (pkey->type != EVP_PKEY_RSA) ||
2260                                 (pkey->pkey.rsa == NULL))
2261                                 {
2262                                 al=SSL_AD_HANDSHAKE_FAILURE;
2263                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2264                                 goto f_err;
2265                                 }
2266                         rsa=pkey->pkey.rsa;
2267                         }
2268
2269                 /* TLS and [incidentally] DTLS{0xFEFF} */
2270                 if (s->version > SSL3_VERSION && s->version != DTLS1_BAD_VER)
2271                         {
2272                         n2s(p,i);
2273                         if (n != i+2)
2274                                 {
2275                                 if (!(s->options & SSL_OP_TLS_D5_BUG))
2276                                         {
2277                                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_TLS_RSA_ENCRYPTED_VALUE_LENGTH_IS_WRONG);
2278                                         goto err;
2279                                         }
2280                                 else
2281                                         p-=2;
2282                                 }
2283                         else
2284                                 n=i;
2285                         }
2286
2287                 /* We must not leak whether a decryption failure occurs because
2288                  * of Bleichenbacher's attack on PKCS #1 v1.5 RSA padding (see
2289                  * RFC 2246, section 7.4.7.1). The code follows that advice of
2290                  * the TLS RFC and generates a random premaster secret for the
2291                  * case that the decrypt fails. See
2292                  * https://tools.ietf.org/html/rfc5246#section-7.4.7.1 */
2293
2294                 /* should be RAND_bytes, but we cannot work around a failure. */
2295                 if (RAND_pseudo_bytes(rand_premaster_secret,
2296                                       sizeof(rand_premaster_secret)) <= 0)
2297                         goto err;
2298                 decrypt_len = RSA_private_decrypt((int)n,p,p,rsa,RSA_PKCS1_PADDING);
2299                 ERR_clear_error();
2300
2301                 /* decrypt_len should be SSL_MAX_MASTER_KEY_LENGTH.
2302                  * decrypt_good will be 0xff if so and zero otherwise. */
2303                 decrypt_good = constant_time_eq_int_8(decrypt_len, SSL_MAX_MASTER_KEY_LENGTH);
2304
2305                 /* If the version in the decrypted pre-master secret is correct
2306                  * then version_good will be 0xff, otherwise it'll be zero.
2307                  * The Klima-Pokorny-Rosa extension of Bleichenbacher's attack
2308                  * (http://eprint.iacr.org/2003/052/) exploits the version
2309                  * number check as a "bad version oracle". Thus version checks
2310                  * are done in constant time and are treated like any other
2311                  * decryption error. */
2312                 version_good = constant_time_eq_8(p[0], (unsigned)(s->client_version>>8));
2313                 version_good &= constant_time_eq_8(p[1], (unsigned)(s->client_version&0xff));
2314
2315                 /* The premaster secret must contain the same version number as
2316                  * the ClientHello to detect version rollback attacks
2317                  * (strangely, the protocol does not offer such protection for
2318                  * DH ciphersuites). However, buggy clients exist that send the
2319                  * negotiated protocol version instead if the server does not
2320                  * support the requested protocol version. If
2321                  * SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. */
2322                 if (s->options & SSL_OP_TLS_ROLLBACK_BUG)
2323                         {
2324                         unsigned char workaround_good;
2325                         workaround_good = constant_time_eq_8(p[0], (unsigned)(s->version>>8));
2326                         workaround_good &= constant_time_eq_8(p[1], (unsigned)(s->version&0xff));
2327                         version_good |= workaround_good;
2328                         }
2329
2330                 /* Both decryption and version must be good for decrypt_good
2331                  * to remain non-zero (0xff). */
2332                 decrypt_good &= version_good;
2333
2334                 /* Now copy rand_premaster_secret over p using
2335                  * decrypt_good_mask. */
2336                 for (i = 0; i < (int) sizeof(rand_premaster_secret); i++)
2337                         {
2338                         p[i] = constant_time_select_8(decrypt_good, p[i],
2339                                                       rand_premaster_secret[i]);
2340                         }
2341
2342                 s->session->master_key_length=
2343                         s->method->ssl3_enc->generate_master_secret(s,
2344                                 s->session->master_key,
2345                                 p,i);
2346                 OPENSSL_cleanse(p,i);
2347                 }
2348         else
2349 #endif
2350 #ifndef OPENSSL_NO_DH
2351                 if (alg_k & (SSL_kEDH|SSL_kDHr|SSL_kDHd))
2352                 {
2353                 int idx = -1;
2354                 EVP_PKEY *skey = NULL;
2355                 if (n)
2356                         n2s(p,i);
2357                 else
2358                         i = 0;
2359                 if (n && n != i+2)
2360                         {
2361                         if (!(s->options & SSL_OP_SSLEAY_080_CLIENT_DH_BUG))
2362                                 {
2363                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DH_PUBLIC_VALUE_LENGTH_IS_WRONG);
2364                                 goto err;
2365                                 }
2366                         else
2367                                 {
2368                                 p-=2;
2369                                 i=(int)n;
2370                                 }
2371                         }
2372                 if (alg_k & SSL_kDHr)
2373                         idx = SSL_PKEY_DH_RSA;
2374                 else if (alg_k & SSL_kDHd)
2375                         idx = SSL_PKEY_DH_DSA;
2376                 if (idx >= 0)
2377                         {
2378                         skey = s->cert->pkeys[idx].privatekey;
2379                         if ((skey == NULL) ||
2380                                 (skey->type != EVP_PKEY_DH) ||
2381                                 (skey->pkey.dh == NULL))
2382                                 {
2383                                 al=SSL_AD_HANDSHAKE_FAILURE;
2384                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_RSA_CERTIFICATE);
2385                                 goto f_err;
2386                                 }
2387                         dh_srvr = skey->pkey.dh;
2388                         }
2389                 else if (s->s3->tmp.dh == NULL)
2390                         {
2391                         al=SSL_AD_HANDSHAKE_FAILURE;
2392                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2393                         goto f_err;
2394                         }
2395                 else
2396                         dh_srvr=s->s3->tmp.dh;
2397
2398                 if (n == 0L)
2399                         {
2400                         /* Get pubkey from cert */
2401                         EVP_PKEY *clkey=X509_get_pubkey(s->session->peer);
2402                         if (clkey)
2403                                 {
2404                                 if (EVP_PKEY_cmp_parameters(clkey, skey) == 1)
2405                                         dh_clnt = EVP_PKEY_get1_DH(clkey);
2406                                 }
2407                         if (dh_clnt == NULL)
2408                                 {
2409                                 al=SSL_AD_HANDSHAKE_FAILURE;
2410                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_DH_KEY);
2411                                 goto f_err;
2412                                 }
2413                         EVP_PKEY_free(clkey);
2414                         pub = dh_clnt->pub_key;
2415                         }
2416                 else
2417                         pub=BN_bin2bn(p,i,NULL);
2418                 if (pub == NULL)
2419                         {
2420                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BN_LIB);
2421                         goto err;
2422                         }
2423
2424                 i=DH_compute_key(p,pub,dh_srvr);
2425
2426                 if (i <= 0)
2427                         {
2428                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_DH_LIB);
2429                         BN_clear_free(pub);
2430                         goto err;
2431                         }
2432
2433                 DH_free(s->s3->tmp.dh);
2434                 s->s3->tmp.dh=NULL;
2435                 if (dh_clnt)
2436                         DH_free(dh_clnt);
2437                 else
2438                         BN_clear_free(pub);
2439                 pub=NULL;
2440                 s->session->master_key_length=
2441                         s->method->ssl3_enc->generate_master_secret(s,
2442                                 s->session->master_key,p,i);
2443                 OPENSSL_cleanse(p,i);
2444                 if (dh_clnt)
2445                         return 2;
2446                 }
2447         else
2448 #endif
2449 #ifndef OPENSSL_NO_KRB5
2450         if (alg_k & SSL_kKRB5)
2451                 {
2452                 krb5_error_code         krb5rc;
2453                 krb5_data               enc_ticket;
2454                 krb5_data               authenticator;
2455                 krb5_data               enc_pms;
2456                 KSSL_CTX                *kssl_ctx = s->kssl_ctx;
2457                 EVP_CIPHER_CTX          ciph_ctx;
2458                 const EVP_CIPHER        *enc = NULL;
2459                 unsigned char           iv[EVP_MAX_IV_LENGTH];
2460                 unsigned char           pms[SSL_MAX_MASTER_KEY_LENGTH
2461                                                + EVP_MAX_BLOCK_LENGTH];
2462                 int                  padl, outl;
2463                 krb5_timestamp          authtime = 0;
2464                 krb5_ticket_times       ttimes;
2465
2466                 EVP_CIPHER_CTX_init(&ciph_ctx);
2467
2468                 if (!kssl_ctx)  kssl_ctx = kssl_ctx_new();
2469
2470                 n2s(p,i);
2471                 enc_ticket.length = i;
2472
2473                 if (n < (long)(enc_ticket.length + 6))
2474                         {
2475                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2476                                 SSL_R_DATA_LENGTH_TOO_LONG);
2477                         goto err;
2478                         }
2479
2480                 enc_ticket.data = (char *)p;
2481                 p+=enc_ticket.length;
2482
2483                 n2s(p,i);
2484                 authenticator.length = i;
2485
2486                 if (n < (long)(enc_ticket.length + authenticator.length + 6))
2487                         {
2488                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2489                                 SSL_R_DATA_LENGTH_TOO_LONG);
2490                         goto err;
2491                         }
2492
2493                 authenticator.data = (char *)p;
2494                 p+=authenticator.length;
2495
2496                 n2s(p,i);
2497                 enc_pms.length = i;
2498                 enc_pms.data = (char *)p;
2499                 p+=enc_pms.length;
2500
2501                 /* Note that the length is checked again below,
2502                 ** after decryption
2503                 */
2504                 if(enc_pms.length > sizeof pms)
2505                         {
2506                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2507                                SSL_R_DATA_LENGTH_TOO_LONG);
2508                         goto err;
2509                         }
2510
2511                 if (n != (long)(enc_ticket.length + authenticator.length +
2512                                                 enc_pms.length + 6))
2513                         {
2514                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2515                                 SSL_R_DATA_LENGTH_TOO_LONG);
2516                         goto err;
2517                         }
2518
2519                 if ((krb5rc = kssl_sget_tkt(kssl_ctx, &enc_ticket, &ttimes,
2520                                         &kssl_err)) != 0)
2521                         {
2522 #ifdef KSSL_DEBUG
2523                         printf("kssl_sget_tkt rtn %d [%d]\n",
2524                                 krb5rc, kssl_err.reason);
2525                         if (kssl_err.text)
2526                                 printf("kssl_err text= %s\n", kssl_err.text);
2527 #endif  /* KSSL_DEBUG */
2528                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2529                                 kssl_err.reason);
2530                         goto err;
2531                         }
2532
2533                 /*  Note: no authenticator is not considered an error,
2534                 **  but will return authtime == 0.
2535                 */
2536                 if ((krb5rc = kssl_check_authent(kssl_ctx, &authenticator,
2537                                         &authtime, &kssl_err)) != 0)
2538                         {
2539 #ifdef KSSL_DEBUG
2540                         printf("kssl_check_authent rtn %d [%d]\n",
2541                                 krb5rc, kssl_err.reason);
2542                         if (kssl_err.text)
2543                                 printf("kssl_err text= %s\n", kssl_err.text);
2544 #endif  /* KSSL_DEBUG */
2545                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2546                                 kssl_err.reason);
2547                         goto err;
2548                         }
2549
2550                 if ((krb5rc = kssl_validate_times(authtime, &ttimes)) != 0)
2551                         {
2552                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, krb5rc);
2553                         goto err;
2554                         }
2555
2556 #ifdef KSSL_DEBUG
2557                 kssl_ctx_show(kssl_ctx);
2558 #endif  /* KSSL_DEBUG */
2559
2560                 enc = kssl_map_enc(kssl_ctx->enctype);
2561                 if (enc == NULL)
2562                     goto err;
2563
2564                 memset(iv, 0, sizeof iv);       /* per RFC 1510 */
2565
2566                 if (!EVP_DecryptInit_ex(&ciph_ctx,enc,NULL,kssl_ctx->key,iv))
2567                         {
2568                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2569                                 SSL_R_DECRYPTION_FAILED);
2570                         goto err;
2571                         }
2572                 if (!EVP_DecryptUpdate(&ciph_ctx, pms,&outl,
2573                                         (unsigned char *)enc_pms.data, enc_pms.length))
2574                         {
2575                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2576                                 SSL_R_DECRYPTION_FAILED);
2577                         goto err;
2578                         }
2579                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2580                         {
2581                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2582                                 SSL_R_DATA_LENGTH_TOO_LONG);
2583                         goto err;
2584                         }
2585                 if (!EVP_DecryptFinal_ex(&ciph_ctx,&(pms[outl]),&padl))
2586                         {
2587                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2588                                 SSL_R_DECRYPTION_FAILED);
2589                         goto err;
2590                         }
2591                 outl += padl;
2592                 if (outl > SSL_MAX_MASTER_KEY_LENGTH)
2593                         {
2594                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2595                                 SSL_R_DATA_LENGTH_TOO_LONG);
2596                         goto err;
2597                         }
2598                 if (!((pms[0] == (s->client_version>>8)) && (pms[1] == (s->client_version & 0xff))))
2599                     {
2600                     /* The premaster secret must contain the same version number as the
2601                      * ClientHello to detect version rollback attacks (strangely, the
2602                      * protocol does not offer such protection for DH ciphersuites).
2603                      * However, buggy clients exist that send random bytes instead of
2604                      * the protocol version.
2605                      * If SSL_OP_TLS_ROLLBACK_BUG is set, tolerate such clients. 
2606                      * (Perhaps we should have a separate BUG value for the Kerberos cipher)
2607                      */
2608                     if (!(s->options & SSL_OP_TLS_ROLLBACK_BUG))
2609                         {
2610                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2611                                SSL_AD_DECODE_ERROR);
2612                         goto err;
2613                         }
2614                     }
2615
2616                 EVP_CIPHER_CTX_cleanup(&ciph_ctx);
2617
2618                 s->session->master_key_length=
2619                         s->method->ssl3_enc->generate_master_secret(s,
2620                                 s->session->master_key, pms, outl);
2621
2622                 if (kssl_ctx->client_princ)
2623                         {
2624                         size_t len = strlen(kssl_ctx->client_princ);
2625                         if ( len < SSL_MAX_KRB5_PRINCIPAL_LENGTH ) 
2626                                 {
2627                                 s->session->krb5_client_princ_len = len;
2628                                 memcpy(s->session->krb5_client_princ,kssl_ctx->client_princ,len);
2629                                 }
2630                         }
2631
2632
2633                 /*  Was doing kssl_ctx_free() here,
2634                 **  but it caused problems for apache.
2635                 **  kssl_ctx = kssl_ctx_free(kssl_ctx);
2636                 **  if (s->kssl_ctx)  s->kssl_ctx = NULL;
2637                 */
2638                 }
2639         else
2640 #endif  /* OPENSSL_NO_KRB5 */
2641
2642 #ifndef OPENSSL_NO_ECDH
2643                 if (alg_k & (SSL_kEECDH|SSL_kECDHr|SSL_kECDHe))
2644                 {
2645                 int ret = 1;
2646                 int field_size = 0;
2647                 const EC_KEY   *tkey;
2648                 const EC_GROUP *group;
2649                 const BIGNUM *priv_key;
2650
2651                 /* initialize structures for server's ECDH key pair */
2652                 if ((srvr_ecdh = EC_KEY_new()) == NULL) 
2653                         {
2654                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2655                             ERR_R_MALLOC_FAILURE);
2656                         goto err;
2657                         }
2658
2659                 /* Let's get server private key and group information */
2660                 if (alg_k & (SSL_kECDHr|SSL_kECDHe))
2661                         { 
2662                         /* use the certificate */
2663                         tkey = s->cert->pkeys[SSL_PKEY_ECC].privatekey->pkey.ec;
2664                         }
2665                 else
2666                         {
2667                         /* use the ephermeral values we saved when
2668                          * generating the ServerKeyExchange msg.
2669                          */
2670                         tkey = s->s3->tmp.ecdh;
2671                         }
2672
2673                 group    = EC_KEY_get0_group(tkey);
2674                 priv_key = EC_KEY_get0_private_key(tkey);
2675
2676                 if (!EC_KEY_set_group(srvr_ecdh, group) ||
2677                     !EC_KEY_set_private_key(srvr_ecdh, priv_key))
2678                         {
2679                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2680                                ERR_R_EC_LIB);
2681                         goto err;
2682                         }
2683
2684                 /* Let's get client's public key */
2685                 if ((clnt_ecpoint = EC_POINT_new(group)) == NULL)
2686                         {
2687                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2688                             ERR_R_MALLOC_FAILURE);
2689                         goto err;
2690                         }
2691
2692                 if (n == 0L) 
2693                         {
2694                         /* Client Publickey was in Client Certificate */
2695
2696                          if (alg_k & SSL_kEECDH)
2697                                  {
2698                                  al=SSL_AD_HANDSHAKE_FAILURE;
2699                                  SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_MISSING_TMP_ECDH_KEY);
2700                                  goto f_err;
2701                                  }
2702                         if (((clnt_pub_pkey=X509_get_pubkey(s->session->peer))
2703                             == NULL) || 
2704                             (clnt_pub_pkey->type != EVP_PKEY_EC))
2705                                 {
2706                                 /* XXX: For now, we do not support client
2707                                  * authentication using ECDH certificates
2708                                  * so this branch (n == 0L) of the code is
2709                                  * never executed. When that support is
2710                                  * added, we ought to ensure the key 
2711                                  * received in the certificate is 
2712                                  * authorized for key agreement.
2713                                  * ECDH_compute_key implicitly checks that
2714                                  * the two ECDH shares are for the same
2715                                  * group.
2716                                  */
2717                                 al=SSL_AD_HANDSHAKE_FAILURE;
2718                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2719                                     SSL_R_UNABLE_TO_DECODE_ECDH_CERTS);
2720                                 goto f_err;
2721                                 }
2722
2723                         if (EC_POINT_copy(clnt_ecpoint,
2724                             EC_KEY_get0_public_key(clnt_pub_pkey->pkey.ec)) == 0)
2725                                 {
2726                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2727                                         ERR_R_EC_LIB);
2728                                 goto err;
2729                                 }
2730                         ret = 2; /* Skip certificate verify processing */
2731                         }
2732                 else
2733                         {
2734                         /* Get client's public key from encoded point
2735                          * in the ClientKeyExchange message.
2736                          */
2737                         if ((bn_ctx = BN_CTX_new()) == NULL)
2738                                 {
2739                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2740                                     ERR_R_MALLOC_FAILURE);
2741                                 goto err;
2742                                 }
2743
2744                         /* Get encoded point length */
2745                         i = *p; 
2746                         p += 1;
2747                         if (n != 1 + i)
2748                                 {
2749                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2750                                     ERR_R_EC_LIB);
2751                                 goto err;
2752                                 }
2753                         if (EC_POINT_oct2point(group, 
2754                             clnt_ecpoint, p, i, bn_ctx) == 0)
2755                                 {
2756                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2757                                     ERR_R_EC_LIB);
2758                                 goto err;
2759                                 }
2760                         /* p is pointing to somewhere in the buffer
2761                          * currently, so set it to the start 
2762                          */ 
2763                         p=(unsigned char *)s->init_buf->data;
2764                         }
2765
2766                 /* Compute the shared pre-master secret */
2767                 field_size = EC_GROUP_get_degree(group);
2768                 if (field_size <= 0)
2769                         {
2770                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE, 
2771                                ERR_R_ECDH_LIB);
2772                         goto err;
2773                         }
2774                 i = ECDH_compute_key(p, (field_size+7)/8, clnt_ecpoint, srvr_ecdh, NULL);
2775                 if (i <= 0)
2776                         {
2777                         SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2778                             ERR_R_ECDH_LIB);
2779                         goto err;
2780                         }
2781
2782                 EVP_PKEY_free(clnt_pub_pkey);
2783                 EC_POINT_free(clnt_ecpoint);
2784                 EC_KEY_free(srvr_ecdh);
2785                 BN_CTX_free(bn_ctx);
2786                 EC_KEY_free(s->s3->tmp.ecdh);
2787                 s->s3->tmp.ecdh = NULL; 
2788
2789                 /* Compute the master secret */
2790                 s->session->master_key_length = s->method->ssl3_enc-> \
2791                     generate_master_secret(s, s->session->master_key, p, i);
2792                 
2793                 OPENSSL_cleanse(p, i);
2794                 return (ret);
2795                 }
2796         else
2797 #endif
2798 #ifndef OPENSSL_NO_PSK
2799                 if (alg_k & SSL_kPSK)
2800                         {
2801                         unsigned char *t = NULL;
2802                         unsigned char psk_or_pre_ms[PSK_MAX_PSK_LEN*2+4];
2803                         unsigned int pre_ms_len = 0, psk_len = 0;
2804                         int psk_err = 1;
2805                         char tmp_id[PSK_MAX_IDENTITY_LEN+1];
2806
2807                         al=SSL_AD_HANDSHAKE_FAILURE;
2808
2809                         n2s(p,i);
2810                         if (n != i+2)
2811                                 {
2812                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2813                                         SSL_R_LENGTH_MISMATCH);
2814                                 goto psk_err;
2815                                 }
2816                         if (i > PSK_MAX_IDENTITY_LEN)
2817                                 {
2818                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2819                                         SSL_R_DATA_LENGTH_TOO_LONG);
2820                                 goto psk_err;
2821                                 }
2822                         if (s->psk_server_callback == NULL)
2823                                 {
2824                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2825                                        SSL_R_PSK_NO_SERVER_CB);
2826                                 goto psk_err;
2827                                 }
2828
2829                         /* Create guaranteed NULL-terminated identity
2830                          * string for the callback */
2831                         memcpy(tmp_id, p, i);
2832                         memset(tmp_id+i, 0, PSK_MAX_IDENTITY_LEN+1-i);
2833                         psk_len = s->psk_server_callback(s, tmp_id,
2834                                 psk_or_pre_ms, sizeof(psk_or_pre_ms));
2835                         OPENSSL_cleanse(tmp_id, PSK_MAX_IDENTITY_LEN+1);
2836
2837                         if (psk_len > PSK_MAX_PSK_LEN)
2838                                 {
2839                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2840                                         ERR_R_INTERNAL_ERROR);
2841                                 goto psk_err;
2842                                 }
2843                         else if (psk_len == 0)
2844                                 {
2845                                 /* PSK related to the given identity not found */
2846                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2847                                        SSL_R_PSK_IDENTITY_NOT_FOUND);
2848                                 al=SSL_AD_UNKNOWN_PSK_IDENTITY;
2849                                 goto psk_err;
2850                                 }
2851
2852                         /* create PSK pre_master_secret */
2853                         pre_ms_len=2+psk_len+2+psk_len;
2854                         t = psk_or_pre_ms;
2855                         memmove(psk_or_pre_ms+psk_len+4, psk_or_pre_ms, psk_len);
2856                         s2n(psk_len, t);
2857                         memset(t, 0, psk_len);
2858                         t+=psk_len;
2859                         s2n(psk_len, t);
2860
2861                         if (s->session->psk_identity != NULL)
2862                                 OPENSSL_free(s->session->psk_identity);
2863                         s->session->psk_identity = BUF_strdup((char *)p);
2864                         if (s->session->psk_identity == NULL)
2865                                 {
2866                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2867                                         ERR_R_MALLOC_FAILURE);
2868                                 goto psk_err;
2869                                 }
2870
2871                         if (s->session->psk_identity_hint != NULL)
2872                                 OPENSSL_free(s->session->psk_identity_hint);
2873                         s->session->psk_identity_hint = BUF_strdup(s->ctx->psk_identity_hint);
2874                         if (s->ctx->psk_identity_hint != NULL &&
2875                                 s->session->psk_identity_hint == NULL)
2876                                 {
2877                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2878                                         ERR_R_MALLOC_FAILURE);
2879                                 goto psk_err;
2880                                 }
2881
2882                         s->session->master_key_length=
2883                                 s->method->ssl3_enc->generate_master_secret(s,
2884                                         s->session->master_key, psk_or_pre_ms, pre_ms_len);
2885                         psk_err = 0;
2886                 psk_err:
2887                         OPENSSL_cleanse(psk_or_pre_ms, sizeof(psk_or_pre_ms));
2888                         if (psk_err != 0)
2889                                 goto f_err;
2890                         }
2891                 else
2892 #endif
2893 #ifndef OPENSSL_NO_SRP
2894                 if (alg_k & SSL_kSRP)
2895                         {
2896                         int param_len;
2897
2898                         n2s(p,i);
2899                         param_len=i+2;
2900                         if (param_len > n)
2901                                 {
2902                                 al=SSL_AD_DECODE_ERROR;
2903                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_A_LENGTH);
2904                                 goto f_err;
2905                                 }
2906                         if (!(s->srp_ctx.A=BN_bin2bn(p,i,NULL)))
2907                                 {
2908                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_BN_LIB);
2909                                 goto err;
2910                                 }
2911                         if (BN_ucmp(s->srp_ctx.A, s->srp_ctx.N) >= 0
2912                                 || BN_is_zero(s->srp_ctx.A))
2913                                 {
2914                                 al=SSL_AD_ILLEGAL_PARAMETER;
2915                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_BAD_SRP_PARAMETERS);
2916                                 goto f_err;
2917                                 }
2918                         if (s->session->srp_username != NULL)
2919                                 OPENSSL_free(s->session->srp_username);
2920                         s->session->srp_username = BUF_strdup(s->srp_ctx.login);
2921                         if (s->session->srp_username == NULL)
2922                                 {
2923                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
2924                                         ERR_R_MALLOC_FAILURE);
2925                                 goto err;
2926                                 }
2927
2928                         if ((s->session->master_key_length = SRP_generate_server_master_secret(s,s->session->master_key))<0)
2929                                 {
2930                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,ERR_R_INTERNAL_ERROR);
2931                                 goto err;
2932                                 }
2933
2934                         p+=i;
2935                         }
2936                 else
2937 #endif  /* OPENSSL_NO_SRP */
2938                 if (alg_k & SSL_kGOST) 
2939                         {
2940                         int ret = 0;
2941                         EVP_PKEY_CTX *pkey_ctx;
2942                         EVP_PKEY *client_pub_pkey = NULL, *pk = NULL;
2943                         unsigned char premaster_secret[32], *start;
2944                         size_t outlen=32, inlen;
2945                         unsigned long alg_a;
2946                         int Ttag, Tclass;
2947                         long Tlen;
2948
2949                         /* Get our certificate private key*/
2950                         alg_a = s->s3->tmp.new_cipher->algorithm_auth;
2951                         if (alg_a & SSL_aGOST94)
2952                                 pk = s->cert->pkeys[SSL_PKEY_GOST94].privatekey;
2953                         else if (alg_a & SSL_aGOST01)
2954                                 pk = s->cert->pkeys[SSL_PKEY_GOST01].privatekey;
2955
2956                         pkey_ctx = EVP_PKEY_CTX_new(pk,NULL);
2957                         EVP_PKEY_decrypt_init(pkey_ctx);
2958                         /* If client certificate is present and is of the same type, maybe
2959                          * use it for key exchange.  Don't mind errors from
2960                          * EVP_PKEY_derive_set_peer, because it is completely valid to use
2961                          * a client certificate for authorization only. */
2962                         client_pub_pkey = X509_get_pubkey(s->session->peer);
2963                         if (client_pub_pkey)
2964                                 {
2965                                 if (EVP_PKEY_derive_set_peer(pkey_ctx, client_pub_pkey) <= 0)
2966                                         ERR_clear_error();
2967                                 }
2968                         /* Decrypt session key */
2969                         if (ASN1_get_object((const unsigned char **)&p, &Tlen, &Ttag, &Tclass, n) != V_ASN1_CONSTRUCTED || 
2970                                 Ttag != V_ASN1_SEQUENCE ||
2971                                 Tclass != V_ASN1_UNIVERSAL) 
2972                                 {
2973                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2974                                 goto gerr;
2975                                 }
2976                         start = p;
2977                         inlen = Tlen;
2978                         if (EVP_PKEY_decrypt(pkey_ctx,premaster_secret,&outlen,start,inlen) <=0) 
2979
2980                                 {
2981                                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,SSL_R_DECRYPTION_FAILED);
2982                                 goto gerr;
2983                                 }
2984                         /* Generate master secret */
2985                         s->session->master_key_length=
2986                                 s->method->ssl3_enc->generate_master_secret(s,
2987                                         s->session->master_key,premaster_secret,32);
2988                         /* Check if pubkey from client certificate was used */
2989                         if (EVP_PKEY_CTX_ctrl(pkey_ctx, -1, -1, EVP_PKEY_CTRL_PEER_KEY, 2, NULL) > 0)
2990                                 ret = 2;
2991                         else
2992                                 ret = 1;
2993                 gerr:
2994                         EVP_PKEY_free(client_pub_pkey);
2995                         EVP_PKEY_CTX_free(pkey_ctx);
2996                         if (ret)
2997                                 return ret;
2998                         else
2999                                 goto err;
3000                         }
3001                 else
3002                 {
3003                 al=SSL_AD_HANDSHAKE_FAILURE;
3004                 SSLerr(SSL_F_SSL3_GET_CLIENT_KEY_EXCHANGE,
3005                                 SSL_R_UNKNOWN_CIPHER_TYPE);
3006                 goto f_err;
3007                 }
3008
3009         return(1);
3010 f_err:
3011         ssl3_send_alert(s,SSL3_AL_FATAL,al);
3012 #if !defined(OPENSSL_NO_DH) || !defined(OPENSSL_NO_RSA) || !defined(OPENSSL_NO_ECDH) || defined(OPENSSL_NO_SRP)
3013 err:
3014 #endif
3015 #ifndef OPENSSL_NO_ECDH
3016         EVP_PKEY_free(clnt_pub_pkey);
3017         EC_POINT_free(clnt_ecpoint);
3018         if (srvr_ecdh != NULL) 
3019                 EC_KEY_free(srvr_ecdh);
3020         BN_CTX_free(bn_ctx);
3021 #endif
3022         return(-1);
3023         }
3024
3025 int ssl3_get_cert_verify(SSL *s)
3026         {
3027         EVP_PKEY *pkey=NULL;
3028         unsigned char *p;
3029         int al,ok,ret=0;
3030         long n;
3031         int type=0,i,j;
3032         X509 *peer;
3033         const EVP_MD *md = NULL;
3034         EVP_MD_CTX mctx;
3035         EVP_MD_CTX_init(&mctx);
3036
3037         n=s->method->ssl_get_message(s,
3038                 SSL3_ST_SR_CERT_VRFY_A,
3039                 SSL3_ST_SR_CERT_VRFY_B,
3040                 -1,
3041                 SSL3_RT_MAX_PLAIN_LENGTH,
3042                 &ok);
3043
3044         if (!ok) return((int)n);
3045
3046         if (s->session->peer != NULL)
3047                 {
3048                 peer=s->session->peer;
3049                 pkey=X509_get_pubkey(peer);
3050                 type=X509_certificate_type(peer,pkey);
3051                 }
3052         else
3053                 {
3054                 peer=NULL;
3055                 pkey=NULL;
3056                 }
3057
3058         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE_VERIFY)
3059                 {
3060                 s->s3->tmp.reuse_message=1;
3061                 if ((peer != NULL) && (type & EVP_PKT_SIGN))
3062                         {
3063                         al=SSL_AD_UNEXPECTED_MESSAGE;
3064                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_MISSING_VERIFY_MESSAGE);
3065                         goto f_err;
3066                         }
3067                 ret=1;
3068                 goto end;
3069                 }
3070
3071         if (peer == NULL)
3072                 {
3073                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_NO_CLIENT_CERT_RECEIVED);
3074                 al=SSL_AD_UNEXPECTED_MESSAGE;
3075                 goto f_err;
3076                 }
3077
3078         if (!(type & EVP_PKT_SIGN))
3079                 {
3080                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_SIGNATURE_FOR_NON_SIGNING_CERTIFICATE);
3081                 al=SSL_AD_ILLEGAL_PARAMETER;
3082                 goto f_err;
3083                 }
3084
3085         if (s->s3->change_cipher_spec)
3086                 {
3087                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_CCS_RECEIVED_EARLY);
3088                 al=SSL_AD_UNEXPECTED_MESSAGE;
3089                 goto f_err;
3090                 }
3091
3092         /* we now have a signature that we need to verify */
3093         p=(unsigned char *)s->init_msg;
3094         /* Check for broken implementations of GOST ciphersuites */
3095         /* If key is GOST and n is exactly 64, it is bare
3096          * signature without length field */
3097         if (n==64 && (pkey->type==NID_id_GostR3410_94 ||
3098                 pkey->type == NID_id_GostR3410_2001) )
3099                 {
3100                 i=64;
3101                 } 
3102         else 
3103                 {       
3104                 if (SSL_USE_SIGALGS(s))
3105                         {
3106                         int rv = tls12_check_peer_sigalg(&md, s, p, pkey);
3107                         if (rv == -1)
3108                                 {
3109                                 al = SSL_AD_INTERNAL_ERROR;
3110                                 goto f_err;
3111                                 }
3112                         else if (rv == 0)
3113                                 {
3114                                 al = SSL_AD_DECODE_ERROR;
3115                                 goto f_err;
3116                                 }
3117 #ifdef SSL_DEBUG
3118 fprintf(stderr, "USING TLSv1.2 HASH %s\n", EVP_MD_name(md));
3119 #endif
3120                         p += 2;
3121                         n -= 2;
3122                         }
3123                 n2s(p,i);
3124                 n-=2;
3125                 if (i > n)
3126                         {
3127                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_LENGTH_MISMATCH);
3128                         al=SSL_AD_DECODE_ERROR;
3129                         goto f_err;
3130                         }
3131         }
3132         j=EVP_PKEY_size(pkey);
3133         if ((i > j) || (n > j) || (n <= 0))
3134                 {
3135                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_WRONG_SIGNATURE_SIZE);
3136                 al=SSL_AD_DECODE_ERROR;
3137                 goto f_err;
3138                 }
3139
3140         if (SSL_USE_SIGALGS(s))
3141                 {
3142                 long hdatalen = 0;
3143                 void *hdata;
3144                 hdatalen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
3145                 if (hdatalen <= 0)
3146                         {
3147                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_INTERNAL_ERROR);
3148                         al=SSL_AD_INTERNAL_ERROR;
3149                         goto f_err;
3150                         }
3151 #ifdef SSL_DEBUG
3152                 fprintf(stderr, "Using TLS 1.2 with client verify alg %s\n",
3153                                                         EVP_MD_name(md));
3154 #endif
3155                 if (!EVP_VerifyInit_ex(&mctx, md, NULL)
3156                         || !EVP_VerifyUpdate(&mctx, hdata, hdatalen))
3157                         {
3158                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY, ERR_R_EVP_LIB);
3159                         al=SSL_AD_INTERNAL_ERROR;
3160                         goto f_err;
3161                         }
3162
3163                 if (EVP_VerifyFinal(&mctx, p , i, pkey) <= 0)
3164                         {
3165                         al=SSL_AD_DECRYPT_ERROR;
3166                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_SIGNATURE);
3167                         goto f_err;
3168                         }
3169                 }
3170         else
3171 #ifndef OPENSSL_NO_RSA 
3172         if (pkey->type == EVP_PKEY_RSA)
3173                 {
3174                 i=RSA_verify(NID_md5_sha1, s->s3->tmp.cert_verify_md,
3175                         MD5_DIGEST_LENGTH+SHA_DIGEST_LENGTH, p, i, 
3176                                                         pkey->pkey.rsa);
3177                 if (i < 0)
3178                         {
3179                         al=SSL_AD_DECRYPT_ERROR;
3180                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_DECRYPT);
3181                         goto f_err;
3182                         }
3183                 if (i == 0)
3184                         {
3185                         al=SSL_AD_DECRYPT_ERROR;
3186                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_RSA_SIGNATURE);
3187                         goto f_err;
3188                         }
3189                 }
3190         else
3191 #endif
3192 #ifndef OPENSSL_NO_DSA
3193                 if (pkey->type == EVP_PKEY_DSA)
3194                 {
3195                 j=DSA_verify(pkey->save_type,
3196                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3197                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.dsa);
3198                 if (j <= 0)
3199                         {
3200                         /* bad signature */
3201                         al=SSL_AD_DECRYPT_ERROR;
3202                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,SSL_R_BAD_DSA_SIGNATURE);
3203                         goto f_err;
3204                         }
3205                 }
3206         else
3207 #endif
3208 #ifndef OPENSSL_NO_ECDSA
3209                 if (pkey->type == EVP_PKEY_EC)
3210                 {
3211                 j=ECDSA_verify(pkey->save_type,
3212                         &(s->s3->tmp.cert_verify_md[MD5_DIGEST_LENGTH]),
3213                         SHA_DIGEST_LENGTH,p,i,pkey->pkey.ec);
3214                 if (j <= 0)
3215                         {
3216                         /* bad signature */
3217                         al=SSL_AD_DECRYPT_ERROR;
3218                         SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3219                             SSL_R_BAD_ECDSA_SIGNATURE);
3220                         goto f_err;
3221                         }
3222                 }
3223         else
3224 #endif
3225         if (pkey->type == NID_id_GostR3410_94 || pkey->type == NID_id_GostR3410_2001)
3226                 {   unsigned char signature[64];
3227                         int idx;
3228                         EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new(pkey,NULL);
3229                         EVP_PKEY_verify_init(pctx);
3230                         if (i!=64) {
3231                                 fprintf(stderr,"GOST signature length is %d",i);
3232                         }       
3233                         for (idx=0;idx<64;idx++) {
3234                                 signature[63-idx]=p[idx];
3235                         }       
3236                         j=EVP_PKEY_verify(pctx,signature,64,s->s3->tmp.cert_verify_md,32);
3237                         EVP_PKEY_CTX_free(pctx);
3238                         if (j<=0) 
3239                                 {
3240                                 al=SSL_AD_DECRYPT_ERROR;
3241                                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,
3242                                         SSL_R_BAD_ECDSA_SIGNATURE);
3243                                 goto f_err;
3244                                 }       
3245                 }
3246         else    
3247                 {
3248                 SSLerr(SSL_F_SSL3_GET_CERT_VERIFY,ERR_R_INTERNAL_ERROR);
3249                 al=SSL_AD_UNSUPPORTED_CERTIFICATE;
3250                 goto f_err;
3251                 }
3252
3253
3254         ret=1;
3255         if (0)
3256                 {
3257 f_err:
3258                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3259                 }
3260 end:
3261         if (s->s3->handshake_buffer)
3262                 {
3263                 BIO_free(s->s3->handshake_buffer);
3264                 s->s3->handshake_buffer = NULL;
3265                 s->s3->flags &= ~TLS1_FLAGS_KEEP_HANDSHAKE;
3266                 }
3267         EVP_MD_CTX_cleanup(&mctx);
3268         EVP_PKEY_free(pkey);
3269         return(ret);
3270         }
3271
3272 int ssl3_get_client_certificate(SSL *s)
3273         {
3274         int i,ok,al,ret= -1;
3275         X509 *x=NULL;
3276         unsigned long l,nc,llen,n;
3277         const unsigned char *p,*q;
3278         unsigned char *d;
3279         STACK_OF(X509) *sk=NULL;
3280
3281         n=s->method->ssl_get_message(s,
3282                 SSL3_ST_SR_CERT_A,
3283                 SSL3_ST_SR_CERT_B,
3284                 -1,
3285                 s->max_cert_list,
3286                 &ok);
3287
3288         if (!ok) return((int)n);
3289
3290         if      (s->s3->tmp.message_type == SSL3_MT_CLIENT_KEY_EXCHANGE)
3291                 {
3292                 if (    (s->verify_mode & SSL_VERIFY_PEER) &&
3293                         (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3294                         {
3295                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3296                         al=SSL_AD_HANDSHAKE_FAILURE;
3297                         goto f_err;
3298                         }
3299                 /* If tls asked for a client cert, the client must return a 0 list */
3300                 if ((s->version > SSL3_VERSION) && s->s3->tmp.cert_request)
3301                         {
3302                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_TLS_PEER_DID_NOT_RESPOND_WITH_CERTIFICATE_LIST);
3303                         al=SSL_AD_UNEXPECTED_MESSAGE;
3304                         goto f_err;
3305                         }
3306                 s->s3->tmp.reuse_message=1;
3307                 return(1);
3308                 }
3309
3310         if (s->s3->tmp.message_type != SSL3_MT_CERTIFICATE)
3311                 {
3312                 al=SSL_AD_UNEXPECTED_MESSAGE;
3313                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_WRONG_MESSAGE_TYPE);
3314                 goto f_err;
3315                 }
3316         p=d=(unsigned char *)s->init_msg;
3317
3318         if ((sk=sk_X509_new_null()) == NULL)
3319                 {
3320                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3321                 goto err;
3322                 }
3323
3324         n2l3(p,llen);
3325         if (llen+3 != n)
3326                 {
3327                 al=SSL_AD_DECODE_ERROR;
3328                 SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_LENGTH_MISMATCH);
3329                 goto f_err;
3330                 }
3331         for (nc=0; nc<llen; )
3332                 {
3333                 n2l3(p,l);
3334                 if ((l+nc+3) > llen)
3335                         {
3336                         al=SSL_AD_DECODE_ERROR;
3337                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3338                         goto f_err;
3339                         }
3340
3341                 q=p;
3342                 x=d2i_X509(NULL,&p,l);
3343                 if (x == NULL)
3344                         {
3345                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_ASN1_LIB);
3346                         goto err;
3347                         }
3348                 if (p != (q+l))
3349                         {
3350                         al=SSL_AD_DECODE_ERROR;
3351                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERT_LENGTH_MISMATCH);
3352                         goto f_err;
3353                         }
3354                 if (!sk_X509_push(sk,x))
3355                         {
3356                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,ERR_R_MALLOC_FAILURE);
3357                         goto err;
3358                         }
3359                 x=NULL;
3360                 nc+=l+3;
3361                 }
3362
3363         if (sk_X509_num(sk) <= 0)
3364                 {
3365                 /* TLS does not mind 0 certs returned */
3366                 if (s->version == SSL3_VERSION)
3367                         {
3368                         al=SSL_AD_HANDSHAKE_FAILURE;
3369                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_NO_CERTIFICATES_RETURNED);
3370                         goto f_err;
3371                         }
3372                 /* Fail for TLS only if we required a certificate */
3373                 else if ((s->verify_mode & SSL_VERIFY_PEER) &&
3374                          (s->verify_mode & SSL_VERIFY_FAIL_IF_NO_PEER_CERT))
3375                         {
3376                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
3377                         al=SSL_AD_HANDSHAKE_FAILURE;
3378                         goto f_err;
3379                         }
3380                 /* No client certificate so digest cached records */
3381                 if (s->s3->handshake_buffer && !ssl3_digest_cached_records(s))
3382                         {
3383                         al=SSL_AD_INTERNAL_ERROR;
3384                         goto f_err;
3385                         }
3386                 }
3387         else
3388                 {
3389                 i=ssl_verify_cert_chain(s,sk);
3390                 if (i <= 0)
3391                         {
3392                         al=ssl_verify_alarm_type(s->verify_result);
3393                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE,SSL_R_CERTIFICATE_VERIFY_FAILED);
3394                         goto f_err;
3395                         }
3396                 }
3397
3398         if (s->session->peer != NULL) /* This should not be needed */
3399                 X509_free(s->session->peer);
3400         s->session->peer=sk_X509_shift(sk);
3401         s->session->verify_result = s->verify_result;
3402
3403         /* With the current implementation, sess_cert will always be NULL
3404          * when we arrive here. */
3405         if (s->session->sess_cert == NULL)
3406                 {
3407                 s->session->sess_cert = ssl_sess_cert_new();
3408                 if (s->session->sess_cert == NULL)
3409                         {
3410                         SSLerr(SSL_F_SSL3_GET_CLIENT_CERTIFICATE, ERR_R_MALLOC_FAILURE);
3411                         goto err;
3412                         }
3413                 }
3414         if (s->session->sess_cert->cert_chain != NULL)
3415                 sk_X509_pop_free(s->session->sess_cert->cert_chain, X509_free);
3416         s->session->sess_cert->cert_chain=sk;
3417         /* Inconsistency alert: cert_chain does *not* include the
3418          * peer's own certificate, while we do include it in s3_clnt.c */
3419
3420         sk=NULL;
3421
3422         ret=1;
3423         if (0)
3424                 {
3425 f_err:
3426                 ssl3_send_alert(s,SSL3_AL_FATAL,al);
3427                 }
3428 err:
3429         if (x != NULL) X509_free(x);
3430         if (sk != NULL) sk_X509_pop_free(sk,X509_free);
3431         return(ret);
3432         }
3433
3434 int ssl3_send_server_certificate(SSL *s)
3435         {
3436         CERT_PKEY *cpk;
3437
3438         if (s->state == SSL3_ST_SW_CERT_A)
3439                 {
3440                 cpk=ssl_get_server_send_pkey(s);
3441                 if (cpk == NULL)
3442                         {
3443                         /* VRS: allow null cert if auth == KRB5 */
3444                         if ((s->s3->tmp.new_cipher->algorithm_auth != SSL_aKRB5) ||
3445                             (s->s3->tmp.new_cipher->algorithm_mkey & SSL_kKRB5))
3446                                 {
3447                                 SSLerr(SSL_F_SSL3_SEND_SERVER_CERTIFICATE,ERR_R_INTERNAL_ERROR);
3448                                 return(0);
3449                                 }
3450                         }
3451
3452                 ssl3_output_cert_chain(s,cpk);
3453                 s->state=SSL3_ST_SW_CERT_B;
3454                 }
3455
3456         /* SSL3_ST_SW_CERT_B */
3457         return ssl_do_write(s);
3458         }
3459
3460 #ifndef OPENSSL_NO_TLSEXT
3461 /* send a new session ticket (not necessarily for a new session) */
3462 int ssl3_send_newsession_ticket(SSL *s)
3463         {
3464         if (s->state == SSL3_ST_SW_SESSION_TICKET_A)
3465                 {
3466                 unsigned char *p, *senc, *macstart;
3467                 const unsigned char *const_p;
3468                 int len, slen_full, slen;
3469                 SSL_SESSION *sess;
3470                 unsigned int hlen;
3471                 EVP_CIPHER_CTX ctx;
3472                 HMAC_CTX hctx;
3473                 SSL_CTX *tctx = s->initial_ctx;
3474                 unsigned char iv[EVP_MAX_IV_LENGTH];
3475                 unsigned char key_name[16];
3476
3477                 /* get session encoding length */
3478                 slen_full = i2d_SSL_SESSION(s->session, NULL);
3479                 /* Some length values are 16 bits, so forget it if session is
3480                  * too long
3481                  */
3482                 if (slen_full > 0xFF00)
3483                         return -1;
3484                 senc = OPENSSL_malloc(slen_full);
3485                 if (!senc)
3486                         return -1;
3487                 p = senc;
3488                 i2d_SSL_SESSION(s->session, &p);
3489
3490                 /* create a fresh copy (not shared with other threads) to clean up */
3491                 const_p = senc;
3492                 sess = d2i_SSL_SESSION(NULL, &const_p, slen_full);
3493                 if (sess == NULL)
3494                         {
3495                         OPENSSL_free(senc);
3496                         return -1;
3497                         }
3498                 sess->session_id_length = 0; /* ID is irrelevant for the ticket */
3499
3500                 slen = i2d_SSL_SESSION(sess, NULL);
3501                 if (slen > slen_full) /* shouldn't ever happen */
3502                         {
3503                         OPENSSL_free(senc);
3504                         return -1;
3505                         }
3506                 p = senc;
3507                 i2d_SSL_SESSION(sess, &p);
3508                 SSL_SESSION_free(sess);
3509
3510                 /* Grow buffer if need be: the length calculation is as
3511                  * follows handshake_header_length +
3512                  * 4 (ticket lifetime hint) + 2 (ticket length) +
3513                  * 16 (key name) + max_iv_len (iv length) +
3514                  * session_length + max_enc_block_size (max encrypted session
3515                  * length) + max_md_size (HMAC).
3516                  */
3517                 if (!BUF_MEM_grow(s->init_buf,
3518                         SSL_HM_HEADER_LENGTH(s) + 22 + EVP_MAX_IV_LENGTH +
3519                         EVP_MAX_BLOCK_LENGTH + EVP_MAX_MD_SIZE + slen))
3520                         return -1;
3521                 p = ssl_handshake_start(s);
3522                 EVP_CIPHER_CTX_init(&ctx);
3523                 HMAC_CTX_init(&hctx);
3524                 /* Initialize HMAC and cipher contexts. If callback present
3525                  * it does all the work otherwise use generated values
3526                  * from parent ctx.
3527                  */
3528                 if (tctx->tlsext_ticket_key_cb)
3529                         {
3530                         if (tctx->tlsext_ticket_key_cb(s, key_name, iv, &ctx,
3531                                                          &hctx, 1) < 0)
3532                                 {
3533                                 OPENSSL_free(senc);
3534                                 return -1;
3535                                 }
3536                         }
3537                 else
3538                         {
3539                         RAND_pseudo_bytes(iv, 16);
3540                         EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL,
3541                                         tctx->tlsext_tick_aes_key, iv);
3542                         HMAC_Init_ex(&hctx, tctx->tlsext_tick_hmac_key, 16,
3543                                         tlsext_tick_md(), NULL);
3544                         memcpy(key_name, tctx->tlsext_tick_key_name, 16);
3545                         }
3546
3547                 /* Ticket lifetime hint (advisory only):
3548                  * We leave this unspecified for resumed session (for simplicity),
3549                  * and guess that tickets for new sessions will live as long
3550                  * as their sessions. */
3551                 l2n(s->hit ? 0 : s->session->timeout, p);
3552
3553                 /* Skip ticket length for now */
3554                 p += 2;
3555                 /* Output key name */
3556                 macstart = p;
3557                 memcpy(p, key_name, 16);
3558                 p += 16;
3559                 /* output IV */
3560                 memcpy(p, iv, EVP_CIPHER_CTX_iv_length(&ctx));
3561                 p += EVP_CIPHER_CTX_iv_length(&ctx);
3562                 /* Encrypt session data */
3563                 EVP_EncryptUpdate(&ctx, p, &len, senc, slen);
3564                 p += len;
3565                 EVP_EncryptFinal(&ctx, p, &len);
3566                 p += len;
3567                 EVP_CIPHER_CTX_cleanup(&ctx);
3568
3569                 HMAC_Update(&hctx, macstart, p - macstart);
3570                 HMAC_Final(&hctx, p, &hlen);
3571                 HMAC_CTX_cleanup(&hctx);
3572
3573                 p += hlen;
3574                 /* Now write out lengths: p points to end of data written */
3575                 /* Total length */
3576                 len = p - ssl_handshake_start(s);
3577                 ssl_set_handshake_header(s, SSL3_MT_NEWSESSION_TICKET, len);
3578                 /* Skip ticket lifetime hint */
3579                 p = ssl_handshake_start(s) + 4;
3580                 s2n(len - 6, p);
3581                 s->state=SSL3_ST_SW_SESSION_TICKET_B;
3582                 OPENSSL_free(senc);
3583                 }
3584
3585         /* SSL3_ST_SW_SESSION_TICKET_B */
3586         return ssl_do_write(s);
3587         }
3588
3589 int ssl3_send_cert_status(SSL *s)
3590         {
3591         if (s->state == SSL3_ST_SW_CERT_STATUS_A)
3592                 {
3593                 unsigned char *p;
3594                 /* Grow buffer if need be: the length calculation is as
3595                  * follows 1 (message type) + 3 (message length) +
3596                  * 1 (ocsp response type) + 3 (ocsp response length)
3597                  * + (ocsp response)
3598                  */
3599                 if (!BUF_MEM_grow(s->init_buf, 8 + s->tlsext_ocsp_resplen))
3600                         return -1;
3601
3602                 p=(unsigned char *)s->init_buf->data;
3603
3604                 /* do the header */
3605                 *(p++)=SSL3_MT_CERTIFICATE_STATUS;
3606                 /* message length */
3607                 l2n3(s->tlsext_ocsp_resplen + 4, p);
3608                 /* status type */
3609                 *(p++)= s->tlsext_status_type;
3610                 /* length of OCSP response */
3611                 l2n3(s->tlsext_ocsp_resplen, p);
3612                 /* actual response */
3613                 memcpy(p, s->tlsext_ocsp_resp, s->tlsext_ocsp_resplen);
3614                 /* number of bytes to write */
3615                 s->init_num = 8 + s->tlsext_ocsp_resplen;
3616                 s->state=SSL3_ST_SW_CERT_STATUS_B;
3617                 s->init_off = 0;
3618                 }
3619
3620         /* SSL3_ST_SW_CERT_STATUS_B */
3621         return(ssl3_do_write(s,SSL3_RT_HANDSHAKE));
3622         }
3623
3624 # ifndef OPENSSL_NO_NEXTPROTONEG
3625 /* ssl3_get_next_proto reads a Next Protocol Negotiation handshake message. It
3626  * sets the next_proto member in s if found */
3627 int ssl3_get_next_proto(SSL *s)
3628         {
3629         int ok;
3630         int proto_len, padding_len;
3631         long n;
3632         const unsigned char *p;
3633
3634         /* Clients cannot send a NextProtocol message if we didn't see the
3635          * extension in their ClientHello */
3636         if (!s->s3->next_proto_neg_seen)
3637                 {
3638                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_WITHOUT_EXTENSION);
3639                 return -1;
3640                 }
3641
3642         n=s->method->ssl_get_message(s,
3643                 SSL3_ST_SR_NEXT_PROTO_A,
3644                 SSL3_ST_SR_NEXT_PROTO_B,
3645                 SSL3_MT_NEXT_PROTO,
3646                 514,  /* See the payload format below */
3647                 &ok);
3648
3649         if (!ok)
3650                 return((int)n);
3651
3652         /* s->state doesn't reflect whether ChangeCipherSpec has been received
3653          * in this handshake, but s->s3->change_cipher_spec does (will be reset
3654          * by ssl3_get_finished). */
3655         if (!s->s3->change_cipher_spec)
3656                 {
3657                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,SSL_R_GOT_NEXT_PROTO_BEFORE_A_CCS);
3658                 return -1;
3659                 }
3660
3661         if (n < 2)
3662                 return 0;  /* The body must be > 1 bytes long */
3663
3664         p=(unsigned char *)s->init_msg;
3665
3666         /* The payload looks like:
3667          *   uint8 proto_len;
3668          *   uint8 proto[proto_len];
3669          *   uint8 padding_len;
3670          *   uint8 padding[padding_len];
3671          */
3672         proto_len = p[0];
3673         if (proto_len + 2 > s->init_num)
3674                 return 0;
3675         padding_len = p[proto_len + 1];
3676         if (proto_len + padding_len + 2 != s->init_num)
3677                 return 0;
3678
3679         s->next_proto_negotiated = OPENSSL_malloc(proto_len);
3680         if (!s->next_proto_negotiated)
3681                 {
3682                 SSLerr(SSL_F_SSL3_GET_NEXT_PROTO,ERR_R_MALLOC_FAILURE);
3683                 return 0;
3684                 }
3685         memcpy(s->next_proto_negotiated, p + 1, proto_len);
3686         s->next_proto_negotiated_len = proto_len;
3687
3688         return 1;
3689         }
3690 # endif
3691
3692 #endif