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